How to use getaddrinfo()?

Kelvin picture Kelvin · Mar 29, 2013 · Viewed 11.9k times · Source

Im trying to make a simple program that takes in a string like www.google.com and returns the ip address...

What i have so far:

char* hostname = new char[www.size()+1];
std::copy(www.begin(), www.end(), hostname);
hostname[www.size()] = '\0';

struct addrinfo new_addr, *res;

getaddrinfo(www.c_str(), SERVICE.c_str(), &new_addr, &res);



cout << new_addr.ai_addr;

What are the 3rd of 4th parameters supposed to do? Does the getaddrinfo function modify the new_addr structure or what? I dont really understand the msdn documentation. After the hostname is resolved I want to connect a socket to it.

Answer

Kelvin picture Kelvin · Mar 29, 2013

What if i leave the third parameter nullified?

Heres the code i developed so far.

    char* hostname = new char[www.size()+1];
copy(www.begin(), www.end(), hostname);
hostname[www.size()] = '\0';

struct addrinfo *res;
struct in_addr addr;

getaddrinfo(hostname, NULL, 0, &res);

addr.S_un = ((struct sockaddr_in *)(res->ai_addr))->sin_addr.S_un;

server.sin_addr.s_addr = inet_addr(inet_ntoa(addr));
server.sin_port = htons(portno);

freeaddrinfo(res);
delete []hostname;

server.sin is declared elsewhere that i use to fill a socket in another method of my sockets class.