I am trying to use libuv to resolve a URL to an IP address. I am using the function uv_getaddrinfo
, which passes an addrinfo
object to my call-back.
Is this callback where I receive the IP address? How do I extract the IP address from the addrinfo
object?
There's utility functions geared towards this, like uv_ipv4_addr
and uv_ipv4_name
depending on what you want broken out of that structure.
Many LibUV functions take an addrinfo
directly, so it's a useful structure to have.
libuv provides uv_ipv4_name
and uv_ipv6_name
. The function you choose depends on the addrinfo
object you have:
if (addrinfo.ai_family == AF_INET) {
// ipv4
char c[17] = { '\0' };
uv_ip4_name((sockaddr_in*)(addrinfo.ai_addr), c, 16);
std::cout << c << std::endl;
} else if (addrinfo.ai_family == AF_INET6) {
// ipv6
char c[40] = { '\0' };
uv_ip6_name((sockaddr_in6*)(addrinfo.ai_addr), c, 39);
std::cout << c << std::endl;
}
You may get multple addrinfo
structs from uv_getaddrinfo
. These are stored a singly-linked list, where the "next" pointer is addrinfo.ai_next
.
This is also helpful: What is the difference between struct addrinfo and struct sockaddr