1

I have a socket server which should receive a message and write an answer. For some messages I want to send a special answer. If the message is for example "Hello" I want to answer "Hi!". Here is a part of my code:

...
char in[2000];
char out[2000];
...
while((read_size = recv(fd, in, 2000, 0)) > 0){

    if(strcmp(in, "Hello") == 0){

        strcpy(out, "Hi!\n");

    }
    else{

        strcpy(out, in);

    }

    write(fd, out, strlen(out));

}
...

But the strcmp() doesn't work fine here. Because when I type in "Hello" there is not only the "Hello" in the in variable, because the length is 2000. But how can I check now, if the received message is "Hello"?

2
  • 4
    recv() doesn't null-terminate the buffer. Commented Jun 16, 2016 at 12:38
  • 1
    Adding to @EOF: Your socket server should only listen to good friends ;-) The visually matching buffer sizes of in and out in your sample, might not match so well in the else branch (someone will try to add or look for the null termination which is not in the buffer and cannot be added if all 2000 chars are filled. It should be better to use strncpy instead of strcpy. See for example Why should you use strncpy instead of strcpy? Commented Jun 16, 2016 at 12:45

1 Answer 1

4

Use strncmp function, which compares the first n bytes of the string:

if (strncmp(in, "Hello", strlen("Hello")) == 0) ...
Sign up to request clarification or add additional context in comments.

3 Comments

What if, before the recv(), the buffer contained "xxxxo\0", and recv() only received "Hell"? Your strncmp() would incorrectly report that recv() received "Hello".
It seems to work with strlen("Hello") as the n. I tried it with read_size, too, but that didnt work.
@EOF gave you the answer in its comment to your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.