Resolving Hostname Using getaddrinfo(...) :: Winsock

kuphryn

Senior member
Jan 7, 2001
400
0
0
Hi.

I am new to winsock program and has began study from Network Programming for Microsoft Windows, Second Edition by Anthony Jones and Jim Ohlund.

I am trying to get a code to basically resolve a hostname to its ip address. For example:

-----
user input: www.microsoft.com
app output: 207.46.230.220
-----

I am able to get the calculation above working using older winsock 1.1+ tool including the use of structure hostent, gethostbyname(), and inet_ntoa().

However, in their book, Jones and Ohlund recommend using the newer winsock tools including getaddrinfo() and getnameinfo(). I cannot figure out how to extract the corresponding IP address from a hostname. Here is the code:

-----
int rc = 0;
addrinfo hints, *result = NULL;
memset(&hints, 0, sizeof(hints));
hints.ai_flags = AI_CANONNAME;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;

if (getaddrinfo(rHName, "21", &hints, &result) != 0)
return false;
else
{

// This is where I need help getting the IP address

m_sIP = (reinterpret_cast<sockaddr *>(result->ai_addr)->sa_data());// ->sa_data(); // inet_ntoa(*(reinterpret_cast<in_addr *>(host->h_addr)));

return = true;
}
-----

In the code above, m_sIP is a character array. What do I have to cast result->ai_addr in order to access the IP address?

Thanks,
Kuphryn
 

kuphryn

Senior member
Jan 7, 2001
400
0
0
Here is the solution to my original problem.

-----
{
m_bVeri = false;

addrinfo hints, *result = NULL;
memset(&hints, 0, sizeof(hints));
hints.ai_flags = AI_PASSIVE;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;

if (getaddrinfo(static_cast<LPCTSTR>(rHName), m_sPort.c_str(), &hints, &result) != 0)
return m_bVeri;

if (getnameinfo(result->ai_addr, result->ai_addrlen, m_sIP, 256, NULL, 0, NI_NUMERICHOST) != 0)
return m_bVeri;

m_bVeri = true;
freeaddrinfo(result);

return m_bVeri;
}

Kuphryn