inet_pton()

Updated: April 19, 2023

Convert a text host address to a numeric address

Synopsis:

#include <sys/socket.h>
#include <arpa/inet.h>

int inet_pton( int af,
               const char * src,
               void * dst );

Arguments:

af
The src address's network family; one of:
AF_INET
IPv4 addresses
AF_INET6
IPv6 addresses
src
A pointer to the text host address that you want to convert. The format of the address is interpreted according to af.
dst
A pointer to a buffer where the function can store the converted address.

Library:

libsocket

Use the -l socket option to qcc to link against this library.

Description:

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.

Note: Many existing implementations of inet_addr() and inet_aton() accept nonstandard input: octal numbers, hexadecimal numbers, and fewer than four numbers. The inet_pton() function doesn't accept these formats.

AF_INET6 addresses

IPv6 addresses must be specified in one of the following standard formats:

Based on:

RFC 2373

Returns:

1
Success.
0
The input isn't a valid address.
-1
An error occurred (errno is set).

Errors:

EAFNOSUPPORT
The af argument isn't one of the supported networking families.

Examples:

#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);
}

Classification:

POSIX 1003.1

Safety:  
Cancellation point No
Interrupt handler No
Signal handler Yes
Thread Yes