setsockopt does not work, but does not return errno

Viewed 776

My code is intended to establish a simple connection between two computers using a socket (the winsock2.h one), but the setsockopt phase does not work (returns a negative value) without a valid errno (a null errno unless I initialize the variable beforehand).

Here is my minified code:

// I include winsock2.h, errno.h and other needed (and less important) stuff

int optval = 1;
errno = 0;

int sock = socket(AF_INET, SOCK_STREAM, 0);
if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) < 0){
    print("TCP socket error, %s", strerr(errno));
    exit(EXIT_FAILURE);
}

When running, the program outputs:

TCP socket error, No error

This output, from my point of view, tells me that, either there is no error and the conditional is mistakenly evaluated (perhaps returning under zero does not mean an error), or something strange happens with the errno (as a reminder, if i did not initialize the errno variable it would be null, perhaps winsock2.h does not use it).

1 Answers

Windows sockets functions don't set errno when they fail.

You need to instead call WSAGetLastError to get the most recent error code and FormatMessage message to get the textual equivalent.

if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) < 0){
    char errbuf[300];
    FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, WSAGetLastError(),
                  0, errbuf, sizeof(errbuf), NULL);
    printf("TCP socket error: %s", errbuf);
}
Related