Search code examples
c++windowssocketsserverreply

C++ Server reply properly


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.


Solution

  • 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
    }