C/C++ Get numeric IP representation with getaddrinfo(1)

Farhan Khan

Active Member

Reaction score: 8
Messages: 110

Hi all,
I am trying to perform two operations and wondering if I can use one libc function to do both. Specifically:
  • Determine if a certain string is an IPv4 or IPv6 address
  • Get its numeric IP representation. (ie, ::1 is 1, is 3232235777)
Currently, I am using getaddrinfo(3) for the first part and inet_pton(3) for the second, as follows:
getaddrinfo("", NULL, &hints, &res);
inet_pton(AF_INET, "", &buf);
unsigned x = htonl(buf);
I was wondering if this could be done in a single operation using getaddrinfo(). I suspect so, because the 3rd argument of getaddrinfo() is a "struct addrinfo *hint", which has a member hint->ai_addr->sa_data[14]. I thought this was the non-htonl version of the IP.

However, whenever I try to use this variable my program crashes with a segmentation fault. Am I doing something wrong here? Can I do both operations using getaddrinfo() alone? Please advise.



Active Member

Reaction score: 35
Messages: 169

At first glance, I would say that hints is an input parameter. You can see the const keyword that preceding it. So getaddrinfo() will never fills the struct hints is pointing on. If you left a NULL pointer for the ai_addr member of *hints, the cause of the segmentation fault is obvious.
getaddrinfo(const char *hostname, const char *servname,
const struct addrinfo *hints, struct addrinfo **res);
You have to look into struct addrinfo **res for using the struct sockaddr *ai_addr that the function may has filled.