Maddy Maddy -4 years ago 112
C Question

Server program not ending when "quit" string entered

I've got a basic linux socket program mostly running that accepts strings from the client to send to the server. When "quit" is typed, my client program ends, but the server one prints out "quit" endlessly until you kill the program. Either I'm not reading the string properly or my logic is off.

Code section...

while (1)
{
//fetch message from client and write to stdout
num_client_bytes = recv(client_sockfd, buf, LEN, 0);

if (-1 == num_client_bytes)
{
perror("server-- recv failed");
}
else
{
printf("client msg: %s", buf);

if (0 == strcmp(buf, "quit\n"))
{
break;
}

}
}

//remove local socket file and close sockets
unlink(SOCKET_NAME);
close(client_sockfd);
close(server_sockfd);
return 0;

Answer Source

You need to memset buf prior to recv

recv will not add '\0' at the end of string read from socket, also you should check if recv read entire 4 bytes, then change:

strcmp(buf, "quit\n")

to

strncmp(buf, "quit\n",4)// if you are not sure client sends \n
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download