inet_ntop()

Convert a numeric network address to a string

Synopsis:

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

const char * inet_ntop( int af,
                        const void * src,
                        char * dst,
                        socklen_t size );

Arguments:

af
The src address's network family; one of:
AF_INET
IPv4 addresses
AF_INET6
IPv6 addresses
src
The numeric network address that you want to convert to a string.
dst
The text string that represents the translated network address. You can use the following constants to allocate buffers of the correct size (they're defined in <netinet/in.h>):
  • INET_ADDRSTRLEN — storage for an IPv4 address
  • INET6_ADDRSTRLEN — storage for an IPv6 address
size
The size of the buffer pointed to by dst.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

The inet_ntop() function converts a numeric network address pointed to by src into a text string in the buffer pointed to by dst.

Returns:

A pointer to the buffer containing the text version of the address, or NULL if an error occurs (errno is set).

Errors:

EAFNOSUPPORT
The value of the af argument isn't a supported network family.
ENOSPC
The dst buffer isn't large enough (according to size) to store the translated address.

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