Cannot set UDP_CHECKSUM_COVERAGE option in Visual C++ (2017)

Viewed 132

I get WSA error code 10022 (invalid argument) when my code reaches the setsockopt() line:

#include <ws2tcpip.h>
#include <MSWSock.h>
#include <stdio.h>

#pragma comment(lib, "Ws2_32.lib")
#pragma comment(lib, "Netapi32.lib")

int main(int argc, char** argv)
{
    int iResult;
    DWORD optValue = TRUE;

    SOCKET s;
    WSADATA wsa;

    //Initialise winsock
    printf("\nInitialising Winsock...");
    if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
    {
        printf("Failed. Error Code : %d", WSAGetLastError());
        exit(EXIT_FAILURE);
    }
    printf("Initialised.\n");

    //create socket
    if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == SOCKET_ERROR)
    {
        printf("socket() failed with error code : %d", WSAGetLastError());
        exit(EXIT_FAILURE);
    }

    // THIS LINE FAILS!
    if (setsockopt(s, IPPROTO_UDP, UDP_CHECKSUM_COVERAGE, (const char *)&optValue, sizeof(optValue)) == -1)
    {
        printf("setsockopt failed with error: %d\n", WSAGetLastError());
        exit(EXIT_FAILURE);
    }

    return 0;
}

This is a stripped down version of my code so it can be copied and run easily.

Can anyone tell me what I'm doing wrong?

1 Answers

It looks like you are not creating your socket correctly.

But, I distrust VC++2017, even having it anywhere on a system, so the following might not help.

winsocks can be very unforgiving. I suggest that you verify that all of your code is done correctly.

First is the s - [in] Descriptor identifying a socket. That looks ok.

Next is the level - [in] Level at which the option is defined. IPPROTO_UDP looks like it worked in identifying a socket. That seems ok, but it is suspicious, I would suggest checking that out and verifying that it is actually working.

Next is optname - [in] Socket option for which the value is to be set. The optname value must be a socket option defined within the specified level, or behavior is undefined. UDP_CHECKSUM_COVERAGE might need to be verified as defined for IPPROTO_UDP. I do not trust Visual C++ 17. I suggest that you check this out.

Next is optval - [in] Pointer to the buffer in which the value for the requested option is specified. (const char *)&optValue . Is that working? How about setting this first before using setsockopt ? How about verifying that this is not null or nullptr and that it does actually exist before using it?

Next is optlen - [in] Size of the optval buffer, in bytes. Again, this is VC++2017 and you might need to set this first before using setsockopt. Then verify that it is set to the correct size before you use it.

If you are using Visual Studio "Express" then some dependencies among other things probably will not be working.

You might find this interesting: Fixing Mswsock.h Issues https://www.exefiles.com/en/h/mswsock-h/

Last but not least try adding #include <winsock2.h> with and without Mswsock.h

Related