If I execute command ping ""
or tracert ""
it resolve my current computer name.
But when I execute below code it resolves computer name as '204.204.204.204'
#include <winsock2.h>
#include <ws2tcpip.h>
#include <string>
#include <iostream>
#pragma comment(lib, "Ws2_32.lib")
void get_computer_name(const std::string& ip_address, std::string& computer_name)
{
WSADATA wsa_data;
u_short port = 27015;
struct sockaddr_in socket_address;
char service_info[NI_MAXSERV] = {};
WSAStartup(MAKEWORD(2, 2), &wsa_data);
socket_address.sin_family = AF_INET;
const auto error_code = InetPtonA(AF_INET, &ip_address[0], &socket_address.sin_addr.s_addr);
socket_address.sin_port = htons(port);
computer_name.resize(NI_MAXHOST);
getnameinfo((struct sockaddr *) &socket_address,
sizeof(socket_address),
&computer_name[0],
NI_MAXHOST, service_info, NI_MAXSERV, NI_NUMERICSERV);
WSACleanup();
}
int main(int argc, wchar_t **argv)
{
std::string computer_name;
get_computer_name("", computer_name);
std::cout << computer_name << std::endl;
return 0;
}
I am curious about why 204.204.204.204?
204 is 0xCC
, a common placeholder for uninitialised memory on some platforms.
I wouldn't put too much stock in this value. The real problem is that you're not checking the return values for any of those API functions, so if they "fail", and their results are thus meaningless, you did not detect that.
I strongly suspect that this is the case here, so you're basically just observing nonsense (probably the result of passing a completely uninitialised sockaddr_in
to getnameinfo
in a debug build).
If no error occurs, the InetPton function returns a value of 1 and the buffer pointed to by the pAddrBuf parameter contains the binary numeric IP address in network byte order.
The InetPton function returns a value of 0 if the pAddrBuf parameter points to a string that is not a valid IPv4 dotted-decimal string or a valid IPv6 address string. Otherwise, a value of -1 is returned, and a specific error code can be retrieved by calling the WSAGetLastError for extended error information.
(ref)