Updated: April 19, 2023 |
Convert a text host address to a numeric address
#include <sys/socket.h> #include <arpa/inet.h> int inet_pton( int af, const char * src, void * dst );
The inet_pton() function converts the standard text representation of the numeric network address (src) into its numeric network byte-order binary form (dst).
The converted address is stored in network byte order in dst. The buffer pointed to by dst must be large enough to hold the numeric address:
Family | Numeric address size |
---|---|
AF_INET | 4 bytes |
AF_INET6 | 16 bytes |
AF_INET addresses
IPv4 addresses must be specified in the standard dotted-decimal form:
ddd.ddd.ddd.ddd
where ddd is a one- to three-digit decimal number between 0 and 255.
AF_INET6 addresses
IPv6 addresses must be specified in one of the following standard formats:
x:x:x:x:x:x:x:x
where x is a hexadecimal value for one of the eight 16-bit pieces of the address. For example:
can be represented as:
x:x:x:x:x:x:d.d.d.d
where x is a hexadecimal value for one of the six high-order 16-bit pieces of the address, and d is a decimal value for one of the four low-order 8-bit pieces of the address (standard AF_INET representation). For example:
Or, in their compressed forms:
Based on:
RFC 2373
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <arpa/inet.h> #include <errno.h> #define INADDR "10.1.0.29" #define IN6ADDR "DEAD:BEEF:7654:3210:FEDC:3210:7654:BA98" int main() { struct in_addr inaddr; struct in6_addr in6addr; char buf[INET_ADDRSTRLEN], buf6[INET6_ADDRSTRLEN]; int rval; if ( (rval = inet_pton(AF_INET, INADDR, &inaddr)) == 0) { printf("Invalid address: %s\n", INADDR); exit(EXIT_FAILURE); } else if (rval == -1) { perror("inet_pton"); exit(EXIT_FAILURE); } if (inet_ntop(AF_INET, &inaddr, buf, sizeof(buf)) != NULL) printf("inet addr: %s\n", buf); else { perror("inet_ntop"); exit(EXIT_FAILURE); } if ( (rval = inet_pton(AF_INET6, IN6ADDR, &in6addr)) == 0) { printf("Invalid address: %s\n", IN6ADDR); exit(EXIT_FAILURE); } else if (rval == -1) { perror("inet_pton"); exit(EXIT_FAILURE); } if (inet_ntop(AF_INET6, &in6addr, buf6, sizeof(buf6)) != NULL) printf("inet6 addr: %s\n", buf6); else { perror("inet_ntop"); exit(EXIT_FAILURE); } return(EXIT_SUCCESS); }
Safety: | |
---|---|
Cancellation point | No |
Interrupt handler | No |
Signal handler | Yes |
Thread | Yes |