[Solved] c++ socket programming : sendto() and recvfrom() error code 10038 & in ‘server’ bind failed with 10038


Error 10038 is WSAENOTSOCK: The descriptor is not a socket.

You are calling socket() and assigning your SOCKET handles inside of if statements, but you are missing adequate parenthesis. They should be like this instead:

if( (receivingSocket = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET )

if( (sendingSocket = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET )

Personally, I hate code that performs assignments inside of if statements like this. I prefer to keep them separate. It is cleaner, less error-prone, and no less efficient from the compiler’s perspective:

receivingSocket = socket(AF_INET, SOCK_DGRAM, 0);
if( receivingSocket == INVALID_SOCKET )

sendingSocket = socket(AF_INET, SOCK_DGRAM, 0);
if( sendingSocket == INVALID_SOCKET )

On a side note:

  1. WSAStartup() does not use WSAGetLastError() for error reporting, it directly returns an error code instead. This is clearly stated in the WSAStartup() documentation.

    int err = WSAStartup(MAKEWORD(2,2),&wsaData);
    if (err != 0)
    {
        cout << "Failed. Error Code : " << err;
        exit(EXIT_FAILURE);
    }
    
  2. your UDP receiver is not checking the return value of bind() for an error before entering the recvfrom() loop.

5

solved c++ socket programming : sendto() and recvfrom() error code 10038 & in ‘server’ bind failed with 10038