connect-function (winsock2.h) doesn't find Host

61 views Asked by At

I'm currently trying to understand how to establish a server-client connection under Windows using the header file "winsock2.h". I have done the "Getting started" from Microsoft (here) and now I have a problem that I can't solve!

The problem is that my program returns at the function connect SOCKET_ERROR (WSAGetLastError == 11001 == WSAHOST_NOT_FOUND) (with "www.google.com").
So I looked up what kind of website was suggested here and then tried this too (www.contoso.com), with the same result

I would be very grateful if someone could explain the problem to me!

constexpr auto DEFAULT_PORT   = "27015";
constexpr auto DEFAULT_BUFLEN = 512;

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

#include <winsock2.h>
#include <ws2tcpip.h>
#include <iostream>

...

WSADATA   wsa_data;
SOCKET    sock;
addrinfo* result = NULL;
addrinfo* ptr = NULL;
addrinfo  hints{};
PCSTR     port = DEFAULT_PORT;

WSAStartup(WINSOCK_VERSION, &wsa_data)

ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;

// Resolve the server address and port
getaddrinfo(host_name, port, &hints, &result)

for (ptr = result; ptr != nullptr; ptr = ptr->ai_next) {

    sock = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);

    if (sock == INVALID_SOCKET) {
        std::cout << "\nERROR: socket failed: " << WSAGetLastError() << std::endl;
        freeaddrinfo(result);
        WSACleanUp();
        return WSAGetLastError();
    }

    if (connect(sock, ptr->ai_addr, (int)ptr->ai_addrlen) == SOCKET_ERROR) {
        closesocket(sock);
        sock = INVALID_SOCKET;
        continue;
    }

    break;
}

freeaddrinfo(result);

if (sock == INVALID_SOCKET) {
    std::cout << "\nERROR: unable to connect to server!\n";
    WSACleanUp();
    return WSAGetLastError();
}

WSACleanUp();

EDIT: forgot to copy the initialize of the port variable

1

There are 1 answers

1
John Omielan On

You have the following line defining the port variable on the stack:

PCSTR     port;

However, you have not initialized, or later set, the value to anything before using it in your getaddrinfo call:

getaddrinfo(host_name, port, &hints, &result)

This parameter is, according to getaddrinfo function (ws2tcpip.h),

[in, optional] pServiceName

A pointer to a NULL-terminated ANSI string that contains either a service name or port number represented as a string.

Since the value is most likely not NULL, the function would try to read from an arbitrary part of memory. This results in no valid service name or port number being found, thus causing it to not be able to find the host.