Home > OS >  WinSock2 cant connect to simple server
WinSock2 cant connect to simple server

Time:11-21

I'm learning networking on windows using C and I get this weird 10038 error

WSADATA wsa;
SOCKET connect_socket;
printf("Initialising Winsock...");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
    printf("Failed. Error Code : %d", WSAGetLastError());
    return 1;
}printf("Initialised.\n");

if (connect_socket = socket(AF_INET, SOCK_STREAM, 0) == INVALID_SOCKET) {
    printf("Could not create socket : %d\n", WSAGetLastError());
    return -1;
}
printf("Socket created.\n");
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(80);
server.sin_addr.s_addr = inet_addr("142.250.184.196");
if (connect(connect_socket, (struct sockaddr*)&server, sizeof(server)) != 0)
{
    printf("connect error : %d\n", WSAGetLastError());
    return 1;
}

printf("Connected\n");

return 0;

nslookup www.google.com -> "142.250.184.196" when trying to run program prints: " Initialising Winsock...Initialised. Socket created. connect error : 10038"

CodePudding user response:

if (connect_socket = socket(AF_INET, SOCK_STREAM, 0) == INVALID_SOCKET) {

Based on the operator precedence in C this means

connect_socket = (socket(AF_INET, SOCK_STREAM, 0) == INVALID_SOCKET)

Thus connect_socket is not the actual socket but the result of the check if the socket is valid. Assuming that socket creation worked then connect_socket will thus be false, i.e. 0.

Since 0 is not a valid TCP socket connect will fail with error 10038:

WSAENOTSOCK
10038
Socket operation on nonsocket. An operation was attempted on something that is not a socket. Either the socket handle parameter did not reference a valid socket, or for select, a member of an fd_set was not valid.

To fix this, first assign to connect_socket, then compare with INVALID_SOCKET.

  • Related