I am working on a socket program and everything seems fine when compiling. First, I compile and start the server, and then compile and start the client. The server will work fine, but when the client starts up, I get an error in the function Connect(). Although the socket looks fine, the client does not connect, and the server does not see a connection attempt.
Error message:
Connect: socket operation on a non-socket
Here is the server side code:
if ((ListeningSocket = socket(AF_INET, SOCK_STREAM,0 )) == -1){
printf("socket failed!\n");
exit(1);
}
else
printf("Server: socket() is OK!\n");
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons(5000);
ServerAddr.sin_addr.s_addr = INADDR_ANY;
memset(&(ServerAddr.sin_zero), '\0', 8);
if (bind (ListeningSocket, (struct sockaddr *)&ServerAddr, sizeof(struct sockaddr))==-1)
{
printf("Server: bind() failed!\n");
exit (1);
}
else
printf("Server: bind() is OK!\n");
if (listen(ListeningSocket,5)== -1){
printf("Server: Error listening on socket\n");
exit (1);
}
else{
printf("Server: listen() is OK, I'm waiting for connections...\n");
printf("Server: accept() is ready...\n");}
sin_size = sizeof(struct sockaddr_in);
NewConnection = accept(ListeningSocket, (struct sockaddr *)&ClientAddr,(socklen_t *)&sin_size);
printf("Server: accept() is OK...\n");
printf("Server: Client connected, ready for receiving and sending data...\n");
.........
....
And here is the client code:
if(SendingSocket = socket(AF_INET, SOCK_STREAM, 0) == -1)
{
printf("Client: socket() failed!");
exit (1);
}
else
printf("Client: socket() is OK!\n");
ClientAddr.sin_family = AF_INET;
ClientAddr.sin_port = htons(5000);
ClientAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
memset(&(ClientAddr.sin_zero), '\0', 8);
if ( connect (SendingSocket, (struct sockaddr *)&ClientAddr,
sizeof(struct sockaddr)) == -1)
{
perror("Connect");
exit(1);
}
else
{
printf("Client: connect() is OK, got connected...\n");
printf("Client: Ready for sending and/or receiving data...\n");
}
....
source
share