Indicate if the text string is an IPv6 address or an IPv4 address using standard C socket APIs

I have a program in which an external component passes me a string containing an IP address. Then I need to turn it into a URI. For IPv4, this is easy; I add http: // and add /. However, for IPv6, I also need to surround it in brackets [].

Is there a standard socket call to define a family of address addresses?

+7
c sockets network-programming
source share
3 answers

Use getaddrinfo () and set the prompt flag AI_NUMERICHOST, family AF_UNSPEC, after successfully returning from getaddrinfo, the resulting addrinfo structure. The ai_family element will be either AF_INET or AF_INET6.

EDIT, a small example

#include <sys/types.h> #include <stdio.h> #include <string.h> #include <sys/socket.h> #include <netdb.h> int main(int argc, char *argv[]) { struct addrinfo hint, *res = NULL; int ret; memset(&hint, '\0', sizeof hint); hint.ai_family = PF_UNSPEC; hint.ai_flags = AI_NUMERICHOST; ret = getaddrinfo(argv[1], NULL, &hint, &res); if (ret) { puts("Invalid address"); puts(gai_strerror(ret)); return 1; } if(res->ai_family == AF_INET) { printf("%s is an ipv4 address\n",argv[1]); } else if (res->ai_family == AF_INET6) { printf("%s is an ipv6 address\n",argv[1]); } else { printf("%s is an is unknown address format %d\n",argv[1],res->ai_family); } freeaddrinfo(res); return 0; } $ ./a.out 127.0.0.1 127.0.0.1 is an ipv4 address $ ./a.out ff01::01 ff01::01 is an ipv6 address 
+13
source share

View. You can use inet_pton() to try to parse the string first as IPv4 ( AF_INET ), then IPv6 ( AF_INET6 ). The return code will let you know if this function was successful, and therefore the line contains the address of the requested type.

For example:

 #include <arpa/inet.h> #include <stdio.h> static int ip_version(const char *src) { char buf[16]; if (inet_pton(AF_INET, src, buf)) { return 4; } else if (inet_pton(AF_INET6, src, buf)) { return 6; } return -1; } int main(int argc, char *argv[]) { for (int i = 1; i < argc; ++i) { printf("%s\t%d\n", argv[i], ip_version(argv[i])); } return 0; } 
+16
source share

Here is the simplest function:

http://tdistler.com/2011/02/25/how-to-test-if-an-address-is-ipv4-or-ipv6

It also processes hostname strings and returns the address type of the first returned DNS record. Set AI_NUMERICHOST to disable hostname stuff.

+1
source share

All Articles