getaddrinfo returns only one IP address for multi-homed host

J

Jaydeep Chovatia

Hi,

I have updated /etc/hosts to add following two IP addresses in it:
10.1.23.1 testmachine.mytest.com
10.1.23.2 testmachine.mytest.com

I have written following c++ program to fetch both these IP Addresses
using getaddrinfo but it returns "10.1.23.1" ip address only during
first iteration (when i = 0) however it successfully returns both the
ip addresses during second iteratio (when i = 1).

Can somebody please explain me why below program returns only one IP
address during first iteration?

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

for(int i = 0; i < 2; i++) {
cout << endl <<
"-------------------------------------------" << endl;
string hostname = "testmachine.mytest.com";
int rc;
struct addrinfo hints, *res, *result;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_CANONNAME | AI_PASSIVE;
rc = getaddrinfo(hostname.c_str(), "9001", &hints,
&result);

if (rc != 0) {
std::stringstream err;
err << "hostToIpAddress got error of [" <<
gai_strerror(rc) << \
"] from getaddrinfo() on hostname ["
<< hostname << "]";
return 0;
}

for (res = result; res != NULL; res = res->ai_next) {
void* ptr;
char addrbuf[256];
int addrbufsz = sizeof(addrbuf);

inet_ntop(res->ai_family, res->ai_addr-
sa_data, addrbuf, addrbufsz);
switch (res->ai_family) {
case AF_INET:
ptr = &((struct sockaddr_in *)
res->ai_addr)->sin_addr;
break;
case AF_INET6:
ptr = &((struct sockaddr_in6
*) res->ai_addr)->sin6_addr;
break;
}
inet_ntop(res->ai_family, ptr, addrbuf,
addrbufsz);

cout<<"hostToIpAddresses:"<<hostname<<":"<<addrbuf<<endl;
}
}

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top