String comparison when using sockets in C

834 views Asked by At

I can't seem to find a solution to this, most people have the following but this doesn't work for me.

int sock_fd;
int new_fd;
int rc;
char recv_client_msg[100];

rc=read(new_fd, recv_client_msg, sizeof(recv_client_msg));

if(rc>0)
 {
   if(strcmp(recv_client_msg, "s1p1")==0) {printf("s1p1\n"); }
   if(recv_client_msg[0]=="s") {printf("m\n");}
 }     

My sockets are completely functional. When the client is open, if I press the "m" key the program prints "m" on the local terminal. However I want to print "s1p1" on the local terminal when I type "s1p1" when I have the client open. However this doesn't happen despite reading previous examples and the compilation being successful.

Any tips would be appreciated

My theory is it may be something to do with the program processing the first character "s", successfully but when I enter "1" the first "s" is overwritten by the "1" rather than takingg up the second slot in the string.

2

There are 2 answers

8
Iharob Al Asimi On

Use memcmp() instead, the strcmp() function requires that both parameters be nul terminated, which is not guaranteed when passing the string through a socket, you can use memcmp() which takes the number of bytes to compare as a parameter.

if (((rc == 4) || (rc == 5)) && (memcmp(recv_client_msg, "s1p1", rc) == 0))
    printf("s1p1\n");

the (rc == 5) test is performed because if the nul termination byte is present, then the comparison should also give true.

6
Giorgi Moniava On

Some notes:

  1. To read/send data over network you need functions such as this and this. Because send and receive not always send/receive how much you told them to.

  2. You seem to use uninitialized variable new_fd which doesn't look nice.

  3. Finally after you have ensured all the data has been received that was sent(using the approach I mentioned in (1)), comparing strings is not issue - you can use just strcmp, assuming strings are null terminated.