C sockets raise error code 22, EINVAL - invalid argument

The sample code below works as a server process. But when I add the line

pid_t childpid; 

below

 struct sockaddr_in servaddr, clientaddr; 

he fails in line

 connectfd = accept(listenfd, (struct sockaddr *) &clientaddr, &clientaddrlen); 

with error code 22, EINVAL is an invalid argument. I am new to C sockets and I could not understand the problem, can you help me?

Thanks.

 #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <linux/in.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> extern int errno; int main() { int clientaddrlen, listenfd, connectfd, bytes_rcvd, listen_queue_size=1; short int port_no = 2000; char buffer[1000]; struct sockaddr_in servaddr, clientaddr; printf("Server running at port #%d\n", port_no); // Create server socket. if ( (listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { fprintf(stderr, "Cannot create server socket! errno=%d \n", errno); exit(-1); } printf("Server socket created\n"); // Bind (attach) this process to the server socket. servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(port_no); bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr)); printf("Server socket is bound to port #%d\n", port_no); // Turn 'listenfd' to a listening socket. Listen queue size is 1. listen(listenfd,listen_queue_size); printf("Server listening with a queue of size %d. \n", listen_queue_size); // Wait for connection(s) from client(s). while (1) { connectfd = accept(listenfd, (struct sockaddr *) &clientaddr, &clientaddrlen); printf("A client has connected\n"); if (recv(connectfd, buffer, sizeof(buffer), 0 ) > 0) printf("Received message: %s\n", buffer); close(connectfd); printf("Server closed connection to client\n"); } close(listenfd); return 0; } 
+6
c sockets
source share
2 answers

I do not see where you initialize clientaddrlen . This is an I / O parameter. You must tell accept() how large the buffer for the address is.

+11
source share

Adding a declaration of an unused variable should, under normal circumstances, not result in a failure. The choice is not broken .

The code you posted cannot behave the way you describe; you are not checking the return value of accept (), since you know that this fails ?. Remember that on Unix / libc systems , errno is usually not installed unless an error occurs, so if accept () does not return -1, errno may contain something .

That said; if you confirm that accept () fails and errno is EINVAL, there are two possibilities according to the man page:

  • Socket does not listen for connections. (Have you checked the return code from listen ()?)
  • Invalid Addrlen parameter (i.e. negative)

EDIT: most important: post a complete example that compiles and demonstrates your problem. Otherwise, we can only guess what the problem is.

+4
source share

All Articles