#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define MAXPENDING 5
#define RCVBUFSIZE 50
void DieWithError(char *errorMessage);
void HandleTCPClient(int cIntSocket);
int main()
{
int servSock;
int clntSock;
struct sockaddr_in ServAddr;
struct sockaddr_in ClntAddr;
unsigned short ServPort;
unsigned int clntLen;
ServPort = 5003;
if ((servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
DieWithError("socket() failed");
memset(&ServAddr, 0, sizeof(ServAddr));
ServAddr.sin_family = AF_INET;
ServAddr.sin_addr.s_addr = htonl(INADDR_ANY);
ServAddr.sin_port = htons(ServPort);
if(bind(servSock, (struct sockaddr *) &ServAddr, sizeof(ServAddr)) < 0)
DieWithError("bind() failed");
if(listen(servSock, MAXPENDING) < 0)
DieWithError("Listen() failed");
for(;;)
{
clntLen = sizeof(ClntAddr);
if ((clntSock = accept(servSock, (struct sockaddr *) &ClntAddr,
&clntLen) < 0))
DieWithError("accept() failed");
printf("Handling client %s\n", inet_ntoa(ClntAddr.sin_addr));
HandleTCPClient(clntSock);
}
}
void HandleTCPClient(int clntSocket)
{
char Buffer[RCVBUFSIZE];
int recvMsgSize;
int sum = 0;
if ((recvMsgSize = recv(clntSocket, Buffer, RCVBUFSIZE, 0)) < 0)
DieWithError("recv() failed");
while (strcmp(Buffer, "EOF"))
{
sum += atoi(Buffer);
printf("%s\n", Buffer);
if ((recvMsgSize = recv(clntSocket, Buffer, RCVBUFSIZE, 0)) < 0)
DieWithError("recv() failed");
}
sprintf(Buffer, "%s\n", sum);
if(send(clntSocket, Buffer, recvMsgSize, 0) < 0)
DieWithError("send() failed");
close(clntSocket);
}
void DieWithError(char *errorMessage)
{
perror(errorMessage);
exit(1);
}
My sockets are invalid
I'm trying to make a server on unix that will recieve numbers from a client, add the numbers and then return the sum to the client, but when I run my server and the client connects I get this as the output.
Handling client 144.96.100.243
recv() failed: Socket operation on non-socket
I have no idea why clntSocket would be a non-socket.
Here is the full source of my server, and I'm using gcc to compile.
If anyone knows what's wrong could you please help?
Thanks in advance for any help.
if ((clntSock = accept(servSock, (struct sockaddr *) &ClntAddr, &clntLen) < 0))DieWithError("accept() failed");
All the lines similar to that need to be changed.
I don't know why but I split it up into this and it worked.
clntSock = accept(servSock, (struct sockaddr *) &ClntAddr, &clntLen);if (clntSock < 0) DieWithError("accept() failed");
Also..DieWithError(...) needs to close the socket.
I had to recompile with a new port number every failure
because that was left out.
EDIT x infinity: I finally got source to work.
not very well though.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement