-2

I want to make a Server that reply to my Sockets. I have a code like this:

#define DEFAULT_BUFLEN 512

    /*...*/
int iResult;
int iSendResult;
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;  

    /*...*/     

iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
if (recvbuf == "hello"){
    iSendResult = send(ClientSocket, "Hi Client", sizeof("Hi Client"), 0);

}else {printf("[ERROR]Unexpected Socket.\n"); }

Now, it doesn't work. and I don't now why. I try to searck something online (whit poor results). How can I make it works? I'm willing to change all the code.

N4meless
  • 5
  • 5
  • `if (recvbuf == "hello")` isn't very likely going to work. Also `recvbuf ` should be a `char` array, then you can use `strcmp("hello",recvbuf ) == 0` as condition. – πάντα ῥεῖ Apr 18 '15 at 11:57
  • Using the value returned by `recv` when sending will in almost all cases not work like you want it to. And you should check the value returned by `recv` for errors. – Some programmer dude Apr 18 '15 at 12:00

1 Answers1

1

You can't compare C-style strings with ==. You're comparing the address of the buffer with the address of a static string literal, which will always be unequal.

You also need to deal with the fact that each read from a stream socket (assuming that's what this is) might give more or less data than you're expecting.

A more correct comparison might be

if (iResult < 0) {
    // Some kind of read error, check errno for details
} else if (iResult == 0) {
    // Socket was closed
} else if (iResult < 5) {
    // Not enough input: read some more or give up
} else if (std::equal(recvbuf, recvbuf+5, "hello")) {
    // Expected input: there might be more data to process
} else {
    // Unexpected input
}
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644