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
You have the following line defining the
portvariable on the stack:However, you have not initialized, or later set, the value to anything before using it in your
getaddrinfocall:This parameter is, according to getaddrinfo function (ws2tcpip.h),
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.