WinSock: Remove data from socket

1.4k views Asked by At

I want to receive data from a socket without specifing a buffer. So I just want to remove x bytes from the incoming data buffer.

I have the following code (truncated):

recv(gSocket, NULL, userDataLength, 0);

But when I execute the code above the return value of recv() is SOCKET_ERROR and WSAGetLastError() returns WSAECONNABORTED. Furthermore my connection get's closed.

Question: Is it not possible, to use the receive function for removing data from the RX buffer of the socket?

1

There are 1 answers

1
Remy Lebeau On BEST ANSWER

I want to receive data from a socket without specifing a buffer.

Sorry, but that is simply not possible. You must provide a buffer to receive the bytes. If you don't want to use the bytes, simply discard the buffer after you have read into it.

I just want to remove x bytes from the incoming data buffer.

There is no API for that. You must read the bytes into a valid buffer. What you do with that buffer afterwards is up to you.

when I execute the code above the return value of recv() is SOCKET_ERROR and WSAGetLastError() returns WSAECONNABORTED.

I would have expected WSAEFAULT instead.

Is it not possible, to use the receive function for removing data from the RX buffer of the socket?

Sure, it is possible. You simply have to read the bytes into a buffer, even if it is just a temporary buffer, eg:

int ignoreBytes(SOCKET sock, int numBytes)
{
    u_char buf[256];
    while (numBytes > 0)
    {
        int numRead = recv(sock, (char*)buf, min(sizeof(buf), numBytes), 0);
        if (numRead <= 0)
            return numRead;
        numBytes -= numRead;
    }
    return 1;
}

ignoreBytes(gSocket, userDataLength);