Mysterious number of chars read with read() in simple chat in C?

208 views Asked by At

I have coded a simple TCP chat in C language. The server's job is to receive messages from the client and to send them back in reverse order. The result should look like this:

Client: "Hello"

Server: "olleH"

When I apply "strlen()" to "olleH", the returned length is not 5, but 7. 7 is also the value returned by the read() function. What am I missing here? I know that char arrays end with a '\0', but that doesn't explain the 2 extra chars.

The loop should end upon receiving the message "FINISH". So, I compare the received message to the char array "FINISH" using strcmp(). They are never recognized as being the same for the reason exposed above. I am receiving a message with 2 extra chars. I've tried comparing the incoming message to "FINISH__" (interpret '_' as a blank space), but it won't work either.

do{

    bzero(buffer, 1000);
    n = read(client_socket, buffer, 1000);
    if (n<0){
        error("ERROR reading socket");
    }

    invert(buffer, inv); //inv is a buffer that stores the inverted array

    n = write(client_socket, inv, n);

    if (n<0){
        error("ERROR writing in socket");
    }

}while (strcmp(buffer, "FINISH\n") != 0);

Thank you for your help.

2

There are 2 answers

1
Amol Saindane On BEST ANSWER

while sending data from server you must be typing Hello then pressing ENTER key which is nothing but \r\n. So client is reading it as Hello\r\n. So you must be getting two characters extra. I hope it works for you. You can check this by looping through input buffer and check whether \r\n is present over there.

0
Preaman On

This post might be useful: C Socket Write adding extra characters

When you are receiving 'n' from read it gives you the sizeof the number of bytes read and not the string length of text read. You are writing 'n' in your write command. I guess should 'Hello' is of length 5, its of size 7. This might explain the size 7. Check what your length is using strlen(buffer) or a equivalent.