2
votes

I've a problem with recv() function that I can't explain: it always returns 0. I've a client/server application in which the server simply has to receive a string from the client through the internet (different pc).
There are no connectivity problems, and I also tried to send a string from server to client: it worked. I search in the blog and what I found, recv() socket function returning data with length as 0, non-blocking recv returns 0 when disconnected, Recv returning zero incorrectly, didn't help me to understand.

Here I post the Network class: Network.h

    class Network
    {
        WSADATA wsaData;
        WORD wVersionRequested;
        int Port;
        unsigned int byteReceived, byteSent; 
        SOCKET listeningSocket, connectedSocket; 
        SOCKADDR_IN serverAddr, senderInfo, clientAddr;
        int caddrlen;

    char buff[DIM];
    string buffer;
    public:
        Network();
        ~Network();

    void Recv();
};


Network.c

void Network::Recv() {
    int n = recv(connectedSocket, buff, strlen(buff), 0);

    setByteReceived(n);
    buffer.assign(buff, n);
    cout << "Buffer is: " << buff << endl; 
    if (byteReceived == 0)
        cout << "\tConnection closed" << endl;
    else if (byteReceived > 0) {
        cout << "\tByte received: " << byteReceived << endl;
        cout << getBuffer() << endl;
    }
    else {
        myFormatMessage(WSAGetLastError());
    }
}


The behaviour in the end is the following: client and server are connected, the server returns 0 from recv(). I tried also to run both programs on the same machine. Thank you for your help.

1
And you know that recv() received 0 exactly how?Sam Varshavchik
I didn't say that :) I know only that recv() returns 0. I tried to use also wireshark to track the network traffic, but I've some problems with it. The behaviour seems different from Linux and I can't see the loopback interface even running the program as administrator. I don't know where the error could be.A. Wolf

1 Answers

3
votes

You have:

void Network::Recv() {
    int n = recv(connectedSocket, buff, strlen(buff), 0);
    ...

If strlen(buff) returns 0 (because buff contains a null byte at index 0), you will be asking recv() to read 0 bytes, so it will return 0 bytes. You should be using sizeof(buff) instead of strlen(buff).