Sending multiple messages via send () recv (), socket programming, C

I am trying to make a program (client) that sends a message to the server at the request of the user. The cut out code follows:

Customer:

int main(int argc, char **argv) { struct sockaddr_in servaddr; int sock = socket(AF_INET, SOCK_STREAM, 0); memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(6789); servaddr.sin_addr.s_addr = inet_addr(<ip_address_of_server>); while(1) { char message[161]; fgets(message, 161, stdin); /* Replacing '\n' with '\0' */ char *tmp = strchr(message, '\n'); if (tmp) *tmp = '\0'; connect(sock, (struct sockaddr *)&servaddr, sizeof(servaddr)); send(sock, message, strlen(message), 0); close(sock); } } 

Server:

 int main(int argc, char **argv) { struct sockaddr_in servaddr; int sock = socket(AF_INET, SOCK_STREAM, 0); memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(6789); bind(sock, (struct sockaddr *)&servaddr, sizeof(servaddr)); listen(sock, 5); while(1) { int clisock = accept(sock, (struct sockaddr *) NULL, NULL); if (clisock >= 0) { int messageLength = 160; char message[messageLength+1]; int in, index = 0, limit = messageLength; while ((in = recv(clisock, &message[index], messageLength, 0)) > 0) { index += in; limit -= in; } printf("%s\n", message); } close(clisock); } } 

Now this works for the first message I sent. But then he cannot make another connection (I get the “Bad file descriptor” error when trying to connect in the client program.) Can someone see what I misunderstood? Thanks:)

+4
source share
3 answers

your client program also makes the same error, the first time you open the socket, but after the first connection you close the socket, so the next time in the loop the socket descriptor is invalid, you need to open the socket again, but which is missing, remove the socket call from above and add the bottom line to the beginning of the while loop

int sock = socket (AF_INET, SOCK_STREAM, 0);

+1
source

The problem is that you are closing the sock listening socket instead of the clisock client socket.

+2
source
 servaddr.sin_addr.s_addr = inet_addr(<ip_address_of_server>); 

instead of the above lines in your client code use

 inet_pton(AF_INET,"<ipofserver>",&servaddr.sin_addr); 

perform error checking for the fllowing function.

+2
source

All Articles