0

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;
LPs
  • 16,045
  • 8
  • 30
  • 61
  • 2
    Are you sure you send the newline as well? Or the string terminator? How *do* you send the strings? – Some programmer dude May 22 '17 at 06:30
  • What does the printf() print and what is the result of strlen() on buf? – Scooter May 22 '17 at 06:33
  • @Someprogrammerdude As far as I know, yes. I don't get rid of the terminating null. –  May 22 '17 at 06:39
  • @Scooter The server side will print the message "quit" endlessly. The result of strlen() on buf is always the correct string. –  May 22 '17 at 06:41
  • @Maddy - Are you sure you posted the correct (complete enough) code? Your description hints at an inner loop, within the `while(1)`... mainly because the code in the question suggests that disconnecting the client should print `server-- recv failed` indefinitely... not `quit`. – Myst May 22 '17 at 06:43
  • Strlen() returns a number - what is it? – Scooter May 22 '17 at 06:44
  • @Scooter On the few strings I tested, it returned 6. Server one returned 6 for "hello" and "quit". Client returned 6 for "hello" and 5 for "quit" –  May 22 '17 at 06:52
  • 1
    Well, a string of length 6 is not going to match "quit\n", which is length 5. – Scooter May 22 '17 at 06:53
  • @Scooter Gotcha. I'll just go the extra step and get rid of the nulls. –  May 22 '17 at 07:10
  • What happens if the server/client recv() returns with, say '2' and has only loaded 'qu' into the buffer? – ThingyWotsit May 22 '17 at 07:48

1 Answers1

2

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
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
Pras
  • 4,047
  • 10
  • 20