A better way to do this is with getaddrinfo
, something like
struct addrinfo params = { 0 };
params.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV; // adjust
params.ai_family = AF_UNSPEC;
params.ai_socktype = SOCK_STREAM; // adjust
params.ai_protocol = IPPROTO_TCP; // adjust
struct addrinfo *addrs;
int status = getaddrinfo(ip.c_str(), port.c_str(), ¶ms, &addrs);
if (status == EAI_SYSTEM) {
fprintf(stderr, "%s:%s: %s\n", ip.c_str(), port.c_str(), strerror(errno));
return -1;
} else if (status) {
fprintf(stderr, "%s:%s: %s\n", ip.c_str(), port.c_str(), gai_strerror(status));
return -1;
}
for (struct addrinfo *ai = addrs; ai; ai = ai->ai_next) {
// do something with ai->ai_addr etc here
}
freeaddrinfo(addrs);
return 0;
You'll need to adjust the lines marked "adjust" for your application. You'll also need to supply a port number (inconveniently, it takes this as a string, because it can also accept a protocol name).
The advantages of doing it this way are: Each entry in the addrs
linked list has all the data you need to create and connect a socket to that address; it seamlessly handles IPv6 for you; and, if you take out the AI_NUMERICHOST
, it seamlessly handles domain names for you as well.