inet pton

Jump to: navigation, search

Table of Contents >> IPv6 Programmer's Reference

#include <trsocket.h>

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

Function Description

This function supports both IPv4 and IPv6. Refer to [RFC 2553]. Converts an IP address from the standard text presentation format to the binary format.


  • af
    address family of the IP address specified by src. This is either AF_INET (IPv4) or AF_INET6 (IPv6).
  • src
    IP address to convert as null-terminated ASCII text. The format of the address must match the address family.
  • dst
    Pointer to a buffer where the binary format of the converted IP address will be stored by this function. The memory that this points to must be allocated by the caller, i.e. a local variable in the caller’s address space, and must match the size requirements of the address family (i.e. 4 bytes for AF_INET, 16 bytes for AF_INET6).


  • 1
  • 0
    Failure. The input is not a valid IPv4 dotted-decimal string or a valid IPv6 address string.
  • -1
    Failure. af was set to an invalid value for address family; valid values are AF_INET and AF_INET6. The specific error code can be retrieved by calling tfGetSocketError() with -1.

Example Usage

struct sockaddr_storage ipv4Addr;
struct sockaddr_storage ipv6Addr;
struct sockaddr_storage ipv6Addr2;
struct sockaddr_in6 *ipv6AddrPtr;
ttUserInterface interfaceHandle;
int errorCode;
interfaceHandle = tfAddInterface(...);
/* do necessary initialization of sockaddr_storage structure */
tfMemSet(&ipv4Addr, 0, sizeof(struct sockaddr_storage));
ipv4Addr.ss_family = AF_INET; /* IPv4 address */
ipv4Addr.ss_len = sizeof(struct sockaddr_storage);
tfMemSet(&ipv6Addr, 0, sizeof(struct sockaddr_storage));
ipv6Addr.ss_family = AF_INET6; /* IPv6 address */
ipv6Addr.ss_len = sizeof(struct sockaddr_storage);
/* setup to use the IPv4 address with the BSD socket APIs */
errorCode = inet_pton(
    (void*) &ipv4Addr.addr.ipv4.sin_addr);
/* setup to use the link-local scope IPv6 address
 * fe80:0000:0000:0000:02ea:c0ff:fef0:0860 with the BSD socket APIs
errorCode = inet_pton(
    (void*) &ipv6Addr.addr.ipv6.sin6_addr);
/* do the same thing is a way which is completely BSD-compliant (i.e.
 * without the Treck extensions to sockaddr_storage), and
 * abbreviate the IPv6 address to a shorter form
tfMemSet(&ipv6Addr2, 0, sizeof(struct sockaddr_storage));
ipv6AddrPtr = (struct sockaddr_in6 *) &ipv6Addr2;
ipv6AddrPtr->sin6_family = AF_INET6; /* IPv6 address */
ipv6AddrPtr->sin6_len = sizeof(struct sockaddr_in6);
errorCode = inet_pton(
    (void*) &ipv6AddrPtr->sin6_addr);
/* WARNING: this isn't good enough, because the address is link-local
 * scope. We must also set the sin6_scope_id field to identify the
 * interface that it is scoped to.
errorCode = tf6SockaddrSetScopeId(

Table of Contents >> IPv6 Programmer's Reference