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"?

Eliahu Aaron
  • 4,103
  • 5
  • 27
  • 37
Nono
  • 1,073
  • 4
  • 23
  • 46
  • 4
    `recv()` doesn't null-terminate the buffer. – EOF Jun 16 '16 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?](http://stackoverflow.com/questions/1258550/why-should-you-use-strncpy-instead-of-strcpy) – Dilettant Jun 16 '16 at 12:45

1 Answers1

4

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

if (strncmp(in, "Hello", strlen("Hello")) == 0) ...
Mattia F.
  • 1,720
  • 11
  • 21
  • 1
    What if, before the `recv()`, the buffer contained `"xxxxo\0"`, and `recv()` only received `"Hell"`? Your `strncmp()` would incorrectly report that `recv()` received `"Hello"`. – EOF Jun 16 '16 at 12:40
  • It seems to work with strlen("Hello") as the n. I tried it with read_size, too, but that didnt work. – Nono Jun 16 '16 at 12:54
  • @EOF gave you the answer in its comment to your question. – LPs Jun 16 '16 at 15:04