See RFC 2373 for further details on the representation of IPv6 addresses.
RETURN VALUE
inet_pton() returns 1 on success (network address was successfully converted). 0 is returned if src does not contain a
character string representing a valid network address in the specified address family. If af does not contain a valid
address family, -1 is returned and errno is set to EAFNOSUPPORT.
CONFORMING TO
POSIX.1-2001.
NOTES
Unlike inet_aton(3) and inet_addr(3), inet_pton() supports IPv6 addresses. On the other hand, inet_pton() only accepts
IPv4 addresses in dotted-decimal notation, whereas inet_aton(3) and inet_addr(3) allow the more general numbers-and-dots
notation (hexadecimal and octal number formats, and formats that don't require all four bytes to be explicitly written).
For an interface that handles both IPv6 addresses, and IPv4 addresses in numbers-and-dots notation, see getaddrinfo(3).
BUGS
AF_INET6 does not recognize IPv4 addresses. An explicit IPv4-mapped IPv6 address must be supplied in src instead.
#include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { unsigned char buf[sizeof(struct in6_addr)]; int domain, s; char str[INET6_ADDRSTRLEN]; if (argc != 3) { fprintf(stderr, "Usage: %s {i4|i6|<num>} string\n", argv[0]); exit(EXIT_FAILURE); } domain = (strcmp(argv[1], "i4") == 0) ? AF_INET : (strcmp(argv[1], "i6") == 0) ? AF_INET6 : atoi(argv[1]); s = inet_pton(domain, argv[2], buf); if (s <= 0) { if (s == 0) fprintf(stderr, "Not in presentation format"); else perror("inet_pton"); exit(EXIT_FAILURE); } if (inet_ntop(domain, buf, str, INET6_ADDRSTRLEN) == NULL) { perror("inet_ntop"); exit(EXIT_FAILURE); } printf("%s\n", str); exit(EXIT_SUCCESS); }