[Previous] [Contents] [Index] [Next]

inet_pton()

Convert a text host address to a numeric network address

Synopsis:

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

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

Library:

socket3r.lib, socket3s.lib

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 af argument specifies the networking family of the address:

AF_INET
IPv4 addresses
AF_INET6
IPv6 addresses

The 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:

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:

Standard Unix, POSIX 1003.1g (draft)

Safety:
Interrupt handler Yes
Signal handler Yes
Thread Yes

See also:

inet_ntop()


[Previous] [Contents] [Index] [Next]