RFC 2553
Basic Socket Interface Extensions for IPv6
RFC 2553: Basic Socket Interface Extensions for IPv6 π
okay bestie, this is the RFC that tells the sockets API how to handle IPv6 π
- Number: RFC 2553
- Network Working Group: written by R. Gilligan (FreeGate), S. Thomson (Bellcore), J. Bound (Compaq) and W. Stevens (Consultant) β¨
- Category: Informational πΈ
- Date: March 1999
- Obsoletes: RFC 2133 π
Status of this Memo π«Ά
This memo gives information to the Internet community. It is not an Internet standard of any kind. Distribution of this memo is unlimited.
Copyright Notice π
Copyright (C) The Internet Society (1999). All Rights Reserved.
Abstract π¦
So the sockets interface is the de facto API for TCP/IP apps, right? It started out on Unix in the early 1980s, but it has since shown up on a bunch of non-Unix systems too. TCP/IP apps built on sockets have historically been super portable, and we want IPv6 apps to be just as portable π₯Ή. That means the sockets API needs some changes, and this memo is where they're spelled out. The big ones are a new socket address structure for IPv6 addresses, new address conversion functions, and some new socket options. The goal is to give TCP and UDP apps access to the basic IPv6 features they need, multicasting included, while changing as little as possible and keeping existing IPv4 apps fully compatible π₯. The advanced stuff, raw sockets and access to the IPv6 extension headers, is handled in a separate document, [4] β¨.
Table of Contents
Table of Contents π
1. Introduction.................................................3
2. Design Considerations........................................3
2.1 What Needs to be Changed....................................4
2.2 Data Types..................................................5
2.3 Headers.....................................................5
2.4 Structures..................................................5
3. Socket Interface.............................................6
3.1 IPv6 Address Family and Protocol Family.....................6
3.2 IPv6 Address Structure......................................6
3.3 Socket Address Structure for 4.3BSD-Based Systems...........7
3.4 Socket Address Structure for 4.4BSD-Based Systems...........8
3.5 The Socket Functions........................................9
3.6 Compatibility with IPv4 Applications.......................10
3.7 Compatibility with IPv4 Nodes..............................10
3.8 IPv6 Wildcard Address......................................11
3.9 IPv6 Loopback Address......................................12
3.10 Portability Additions.....................................13
4. Interface Identification....................................16
4.1 Name-to-Index..............................................16
4.2 Index-to-Name..............................................17
4.3 Return All Interface Names and Indexes.....................17
4.4 Free Memory................................................18
5. Socket Options..............................................18
5.1 Unicast Hop Limit..........................................18
5.2 Sending and Receiving Multicast Packets....................19
6. Library Functions...........................................21
6.1 Nodename-to-Address Translation............................21
6.2 Address-To-Nodename Translation............................24
6.3 Freeing memory for getipnodebyname and getipnodebyaddr.....26
6.4 Protocol-Independent Nodename and Service Name Translation.26
6.5 Socket Address Structure to Nodename and Service Name......29
6.6 Address Conversion Functions...............................31
6.7 Address Testing Macros.....................................32
7. Summary of New Definitions..................................33
8. Security Considerations.....................................35
9. Year 2000 Considerations....................................35
Changes From RFC 2133..........................................35
Acknowledgments................................................38
References.....................................................39
Authors' Addresses.............................................40
Full Copyright Statement.......................................41
1. Introduction β¨
IPv4 addresses are 32 bits long, but IPv6 interfaces get identified by 128-bit addresses π. The sockets interface makes the size of an IP address super visible to apps, and basically every TCP/IP app on BSD-based systems knows exactly how big an IP address is. So any part of the API that exposes addresses has to change to fit the bigger IPv6 size. IPv6 also brings new features, like traffic class and flowlabel, and some of those need to be visible to apps through the API too π¦. This memo defines a set of extensions to the socket interface that handle the bigger addresses and the new IPv6 features.
2. Design Considerations π
There are a few important things to keep in mind when changing this well-worn API:
- The API changes should give both source and binary compatibility for programs written against the original API. In other words, existing program binaries should keep working on a system that supports the new API. Existing apps that get recompiled and run on that system should also keep working. Honestly, the whole point is that the IPv6 API changes should not break existing programs π . One extra way for implementations to check this is to protect the new symbols with Feature Test Macros, as described in IEEE Std 1003.1. (This RFC does not define those Feature Test Macros.)
- The changes to the API should be as small as possible, so converting existing IPv4 apps to IPv6 stays easy π.
- Where possible, apps should be able to use this API to talk to both IPv6 and IPv4 hosts. Apps should not have to know which type of host they're talking to π«Ά.
- IPv6 addresses carried in data structures should be 64-bit aligned. This matters for getting the best performance on 64-bit machine architectures π.
Because IPv4 compatibility matters so much in this API, these extensions are explicitly designed to run on machines with complete support for both IPv4 and IPv6 β¨. A subset of this API could probably work on systems that support only IPv6, but this memo doesn't cover that π.
2.1 What Needs to be Changed π
The socket interface API has a few distinct parts:
- Core socket functions.
- Address data structures.
- Name-to-address translation functions.
- Address conversion functions.
The core socket functions are the ones that handle things like setting up and tearing down TCP connections, and sending and receiving UDP packets. They were designed to be transport independent π§. When protocol addresses get passed as function arguments, they travel through opaque pointers. Each protocol that the socket functions support has its own protocol-specific address data structure. When apps use the socket functions, they have to cast pointers to those protocol-specific address structures into pointers to the generic "sockaddr" address structure π. The socket functions don't need to change for IPv6, but a new IPv6-specific address data structure is needed.
The "sockaddr_in" structure is the protocol-specific data structure for IPv4. It has 8 octets of unused space, and it's really tempting to reuse that space to adapt sockaddr_in for IPv6. Sadly, that doesn't work π. sockaddr_in isn't big enough to hold the 16-octet IPv6 address plus the other stuff it needs to carry, like the address family and port number. So a brand new address data structure has to be defined for IPv6 π.
IPv6 addresses are scoped [2], so they could be link-local, site, organization, global, or other scopes that aren't defined yet π. To let apps identify a set of interfaces for a specific scope, the IPv6 sockaddr_in structure must support a field that an implementation can use to identify the set of interfaces that gives the scope for an IPv6 address π₯.
The name-to-address translation functions in the socket interface are gethostbyname() and gethostbyaddr(). These stay as they are, and new functions get defined to support both IPv4 and IPv6 π. The POSIX 1003.g draft [3] also specifies a new nodename-to-address translation function that's protocol independent. That function works with IPv4 and IPv6 too π¦.
The address conversion functions, inet_ntoa() and inet_addr(), convert IPv4 addresses between binary and printable form. They're pretty specific to 32-bit IPv4 addresses π. So we designed two analogous functions that convert both IPv4 and IPv6 addresses. They take an address type parameter so they can be extended to other protocol families later β¨.
A few miscellaneous features are needed for IPv6 too. New interfaces are needed to support the IPv6 traffic class, flow label, and hop limit header fields. New socket options are needed to control sending and receiving IPv6 multicast packets πΈ.
The socket interface will get enhanced in the future to give access to other IPv6 features. Those extensions are described in [4] π.
2.2 Data Types π§
The data types of the structure elements in this memo are meant to be examples, not absolute requirements π . Whenever possible, the data types come from Draft 6.6 (March 1997) of POSIX 1003.1g. uintN_t means an unsigned integer of exactly N bits (for example, uint16_t). We also assume the argument data types from 1003.1g when possible. For instance, the final argument to setsockopt() is a size_t value. Whenever buffer sizes are specified, the POSIX 1003.1 size_t data type is used, like the two length arguments to getnameinfo() β¨.
2.3 Headers π
When function prototypes and structures are shown, we also show the headers that must be #included so the item gets defined π«Ά.
2.4 Structures π¦
When structures are described, the members shown are the ones that must appear in an implementation. An implementation can also define additional, nonstandard members. As an extra precaution, nonstandard members could be verified by Feature Test Macros, as described in IEEE Std 1003.1. (This RFC does not define those Feature Test Macros.) π
The members of a structure are shown in the recommended ordering, based on alignment considerations for multibyte members. An implementation may still order the members differently π.
3. Socket Interface π§
This section specifies the socket interface changes for IPv6 π.
3.1 IPv6 Address Family and Protocol Family β¨
okay so, a brand new address family name, AF_INET6, gets defined in <sys/socket.h> π. The AF_INET6 definition is what tells the difference between the original sockaddr_in address data structure and the new sockaddr_in6 one π
.
A new protocol family name, PF_INET6, also gets defined in <sys/socket.h> π¦. Like most of the other protocol family names, this one usually ends up with the same value as its matching address family name:
#define PF_INET6 AF_INET6
PF_INET6 is what goes in the first argument to the socket() function when you want to say "hey, make me an IPv6 socket" π«Ά.
3.2 IPv6 Address Structure π
A new in6_addr structure holds a single IPv6 address, and it gets defined as soon as you include <netinet/in.h> πΈ:
struct in6_addr {
uint8_t s6_addr[16]; /* IPv6 address */
};
This struct contains an array of sixteen 8-bit elements, which together make up one 128-bit IPv6 address. The address is stored in network byte order π₯.
The in6_addr structure above is usually implemented with an embedded union that has extra fields to force the desired alignment level, kind of like the BSD implementations of "struct in_addr". Those extra details are left out here to keep things simple π.
Here's an example:
struct in6_addr {
union {
uint8_t _S6_u8[16];
uint32_t _S6_u32[4];
uint64_t _S6_u64[2];
} _S6_un;
};
#define s6_addr _S6_un._S6_u8
3.3 Socket Address Structure for 4.3BSD-Based Systems π
okay so in the socket interface, each protocol suite gets its own protocol-specific data structure to carry its addresses. Each of those can be cast into one protocol-independent structure, the "sockaddr" structure π§. Every one of them has a "family" field that overlays the sa_family of the sockaddr data structure, and that field tells you what type of data structure you're looking at π.
The sockaddr_in structure is the protocol-specific address data structure for IPv4. Applications use it to pass addresses to and from the system in the socket functions. The sockaddr_in6 structure below holds IPv6 addresses, and it gets defined as soon as you include the <netinet/in.h> header β¨:
struct sockaddr_in6 {
sa_family_t sin6_family; /* AF_INET6 */
in_port_t sin6_port; /* transport layer port # */
uint32_t sin6_flowinfo; /* IPv6 traffic class & flow info */
struct in6_addr sin6_addr; /* IPv6 address */
uint32_t sin6_scope_id; /* set of interfaces for a scope */
};
This structure is designed to be compatible with the sockaddr data structure used in the 4.3BSD release. It's giving compatibility π«Ά.
The sin6_family field identifies this as a sockaddr_in6 structure. It overlays the sa_family field when the buffer gets cast to a sockaddr data structure. The value of this field must be AF_INET6.
The sin6_port field holds the 16-bit UDP or TCP port number. It's used in exactly the same way as the sin_port field of the sockaddr_in structure. The port number is stored in network byte order.
The sin6_flowinfo field is a 32-bit field that holds two pieces of information: the traffic class and the flow label. The contents and interpretation of this member are specified in [1]. The sin6_flowinfo field SHOULD be set to zero by an implementation before an application uses the sockaddr_in6 structure on receive operations. π
The sin6_addr field is a single in6_addr structure (the one from the previous section). It holds one 128-bit IPv6 address, stored in network byte order π.
The elements in this structure are ordered on purpose. When the sin6_addr field is aligned on a 64-bit boundary, the start of the structure ends up aligned on a 64-bit boundary too. That's done for optimum performance on 64-bit architectures, which is honestly iconic π₯.
The sin6_scope_id field is a 32-bit integer that identifies a set of interfaces that fit the scope of the address in the sin6_addr field. For a link-scope sin6_addr, sin6_scope_id would be an interface index. For a site-scope sin6_addr, sin6_scope_id would be a site identifier. How sin6_scope_id maps to an interface (or a set of interfaces) is left to the implementation and to future specifications on site identifiers π¦.
β οΈ Heads up bestie: thesockaddr_in6structure will usually be bigger than the genericsockaddrstructure. On many existing implementations,sizeof(struct sockaddr_in)equalssizeof(struct sockaddr), and both are 16 bytes. Any existing code that makes that assumption needs a careful look when it gets converted to IPv6 π.
3.4 Socket Address Structure for 4.4BSD-Based Systems π
the 4.4BSD release has a small but incompatible change to the socket interface. The sa_family field of the sockaddr data structure went from a 16-bit value to an 8-bit value, and the space it freed up got used for a length field called sa_len π§. Because of that, the sockaddr_in6 structure from the previous section can't be correctly cast into the newer sockaddr data structure π. So for systems based on 4.4BSD, there's an alternative IPv6 address data structure, and it's defined when you include the <netinet/in.h> header:
struct sockaddr_in6 {
uint8_t sin6_len; /* length of this struct */
sa_family_t sin6_family; /* AF_INET6 */
in_port_t sin6_port; /* transport layer port # */
uint32_t sin6_flowinfo; /* IPv6 flow information */
struct in6_addr sin6_addr; /* IPv6 address */
uint32_t sin6_scope_id; /* set of interfaces for a scope */
};
The only differences between this one and the 4.3BSD variant are the length field and the family field changing to an 8-bit data type. Every other field is defined exactly the same way as in the structure from the previous section π .
Systems that provide this version of the sockaddr_in6 data structure must also declare SIN6_LEN when they include the <netinet/in.h> header. The macro lets applications figure out whether they're being built on a system that supports the 4.3BSD or 4.4BSD variant of the data structure π.
3.5 The Socket Functions π¦
okay so applications call the socket() function to create a socket descriptor, which represents a communication endpoint. The arguments to socket() tell the system which protocol to use and what format of address structure will be used in the functions that come after. For example, to create an IPv4/TCP socket, an application makes this call:
s = socket(PF_INET, SOCK_STREAM, 0);
To create an IPv4/UDP socket, an application makes this call:
s = socket(PF_INET, SOCK_DGRAM, 0);
Applications can create IPv6/TCP and IPv6/UDP sockets by just using the constant PF_INET6 instead of PF_INET in the first argument. For example, to create an IPv6/TCP socket, an application makes this call:
s = socket(PF_INET6, SOCK_STREAM, 0);
To create an IPv6/UDP socket, an application makes this call:
s = socket(PF_INET6, SOCK_DGRAM, 0);
Once the application has created a PF_INET6 socket, it must use the sockaddr_in6 address structure when it passes addresses into the system. The functions the application uses to pass addresses in are:
bind()
connect()
sendmsg()
sendto()
The system uses the sockaddr_in6 address structure to return addresses to applications that are using PF_INET6 sockets. The functions that return an address from the system to an application are:
accept()
recvfrom()
recvmsg()
getpeername()
getsockname()
No changes to the syntax of the socket functions are needed to support IPv6. That's because all of the "address carrying" functions take an opaque address pointer and carry an address length as a function argument, so they already handle it π«Ά.
3.6 Compatibility with IPv4 Applications π
so, to support the huge base of applications using the original API, system implementations must provide complete source and binary compatibility with that original API. In other words, systems must keep supporting PF_INET sockets and the sockaddr_in address structure. Applications must be able to create IPv4/TCP and IPv4/UDP sockets with the PF_INET constant in the socket() function, as described in the previous section. Applications should also be able to hold a mix of IPv4/TCP, IPv4/UDP, IPv6/TCP and IPv6/UDP sockets at the same time within the same process π.
Applications using the original API should keep working the way they did on systems that only supported IPv4. That means they should keep interoperating with IPv4 nodes πΈ.
3.7 Compatibility with IPv4 Nodes π§
the API also has a different kind of compatibility: the ability for IPv6 applications to interoperate with IPv4 applications π₯. This feature uses the IPv4-mapped IPv6 address format defined in the IPv6 addressing architecture specification [2]. That format lets the IPv4 address of an IPv4 node be represented as an IPv6 address. The IPv4 address is encoded into the low-order 32 bits of the IPv6 address, and the high-order 96 bits hold the fixed prefix 0:0:0:0:0:FFFF. IPv4-mapped addresses are written like this:
::FFFF:<IPv4-address>
These addresses can be generated automatically by the getipnodebyname() function when the specified host has only IPv4 addresses (as described in Section 6.1) β¨.
Applications can use PF_INET6 sockets to open TCP connections to IPv4 nodes, or to send UDP packets to IPv4 nodes. They just encode the destination's IPv4 address as an IPv4-mapped IPv6 address and pass that address, inside a sockaddr_in6 structure, into the connect() or sendto() call π¦. When applications use PF_INET6 sockets to accept TCP connections from IPv4 nodes, or to receive UDP packets from IPv4 nodes, the system returns the peer's address to the application using a sockaddr_in6 structure encoded this way, in the accept(), recvfrom(), or getpeername() call π.
Few applications will likely need to know which type of node they're interoperating with. But for the ones that do need to know, the IN6_IS_ADDR_V4MAPPED() macro, defined in Section 6.7, is provided π
.
3.8 IPv6 Wildcard Address πΈ
okay bestie, bind() lets apps pick the source IP address for UDP packets and TCP connections, but honestly most apps just want the system to pick one for them π
With IPv4, you pass the symbolic constant INADDR_ANY (aka the "wildcard" address) in the bind() call, or you skip bind() entirely β¨
Since the IPv6 address type is a structure (struct in6_addr), a symbolic constant can initialize an IPv6 address variable, but it can't be used in an assignment π So systems give you the IPv6 wildcard address in two forms π¦
Form one is a global variable called in6addr_any, which is an in6_addr structure. Its extern declaration is in <netinet/in.h>:
extern const struct in6_addr in6addr_any;
Apps use in6addr_any pretty much the same way they use INADDR_ANY in IPv4 π«Ά For example, to bind a socket to port 23 but let the system choose the source address, an app could use this code:
struct sockaddr_in6 sin6;
. . .
sin6.sin6_family = AF_INET6;
sin6.sin6_flowinfo = 0;
sin6.sin6_port = htons(23);
sin6.sin6_addr = in6addr_any; /* structure assignment */
. . .
if (bind(s, (struct sockaddr *) &sin6, sizeof(sin6)) == -1)
. . .
The other version is a symbolic constant named IN6ADDR_ANY_INIT, also defined in <netinet/in.h>. This one initializes an in6_addr structure:
struct in6_addr anyaddr = IN6ADDR_ANY_INIT;
Note that this constant can be used only at declaration time. It can not be used to assign a previously declared in6_addr structure. For example, this one does not work:
/* This is the WRONG way to assign an unspecified address */
struct sockaddr_in6 sin6;
. . .
sin6.sin6_addr = IN6ADDR_ANY_INIT; /* will NOT compile */
Be aware that the IPv4INADDR_xxxconstants are all defined in host byte order, but the IPv6IN6ADDR_xxxconstants and the IPv6in6addr_xxxexternals are defined in network byte order. Watch out for this one, bestie π
3.9 IPv6 Loopback Address π
Sometimes apps need to send UDP packets to services on the local node, or open TCP connections to them π In IPv4, they do this with the constant IPv4 address INADDR_LOOPBACK in their connect(), sendto(), or sendmsg() call.
IPv6 has a loopback address too, for reaching local TCP and UDP services π Like the unspecified address, the IPv6 loopback address comes in two forms: a global variable and a symbolic constant.
The global variable is an in6_addr structure named "in6addr_loopback." Its extern declaration is in <netinet/in.h>:
extern const struct in6_addr in6addr_loopback;
Apps use in6addr_loopback the same way they'd use INADDR_LOOPBACK in IPv4 apps (but beware of the byte ordering difference mentioned at the end of the previous section π). For example, to open a TCP connection to the local telnet server, an app could use this code:
struct sockaddr_in6 sin6;
. . .
sin6.sin6_family = AF_INET6;
sin6.sin6_flowinfo = 0;
sin6.sin6_port = htons(23);
sin6.sin6_addr = in6addr_loopback; /* structure assignment */
. . .
if (connect(s, (struct sockaddr *) &sin6, sizeof(sin6)) == -1)
. . .
The symbolic constant is named IN6ADDR_LOOPBACK_INIT, defined in <netinet/in.h>. It can be used at declaration time only. For example:
struct in6_addr loopbackaddr = IN6ADDR_LOOPBACK_INIT;
Just like IN6ADDR_ANY_INIT, this constant can't be used in an assignment to a previously declared IPv6 address variable π
ββοΈ
3.10 Portability Additions π§
One simple addition to the sockets API that can help app writers is the "struct sockaddr_storage". This data structure can make cross-platform, multi-address-family code way easier to write π It's designed with these goals:
- It has a large enough implementation specific maximum size to store the desired set of protocol specific socket address data structures. Specifically, it is at least large enough to accommodate
sockaddr_inandsockaddr_in6and possibly other protocol specific socket addresses too. - It is aligned at an appropriate boundary so protocol specific socket address data structure pointers can be cast to it and access their fields without alignment problems. (e.g. pointers to
sockaddr_in6and/orsockaddr_incan be cast to it and access fields without alignment problems). - It has the initial field(s) isomorphic to the fields of the "struct sockaddr" data structure on that implementation which can be used as a discriminants for deriving the protocol in use. These initial field(s) would on most implementations either be a single field of type "sa_family_t" (isomorphic to sa_family field, 16 bits) or two fields of type uint8_t and sa_family_t respectively, (isomorphic to sa_len and sa_family_t, 8 bits each).
Here's an example implementation design of this data structure π
/*
* Desired design of maximum size and alignment
*/
#define _SS_MAXSIZE 128 /* Implementation specific max size */
#define _SS_ALIGNSIZE (sizeof (int64_t))
/* Implementation specific desired alignment */
/*
* Definitions used for sockaddr_storage structure paddings design.
*/
#define _SS_PAD1SIZE (_SS_ALIGNSIZE - sizeof (sa_family_t))
#define _SS_PAD2SIZE (_SS_MAXSIZE - (sizeof (sa_family_t)+
_SS_PAD1SIZE + _SS_ALIGNSIZE))
struct sockaddr_storage {
sa_family_t __ss_family; /* address family */
/* Following fields are implementation specific */
char __ss_pad1[_SS_PAD1SIZE];
/* 6 byte pad, this is to make implementation
/* specific pad up to alignment field that */
/* follows explicit in the data structure */
int64_t __ss_align; /* field to force desired structure */
/* storage alignment */
char __ss_pad2[_SS_PAD2SIZE];
/* 112 byte pad to achieve desired size, */
/* _SS_MAXSIZE value minus size of ss_family */
/* __ss_pad1, __ss_align fields is 112 */
};
On implementations where the sockaddr data structure includes a "sa_len" field, this data structure would look like this:
/*
* Definitions used for sockaddr_storage structure paddings design.
*/
#define _SS_PAD1SIZE (_SS_ALIGNSIZE -
(sizeof (uint8_t) + sizeof (sa_family_t))
#define _SS_PAD2SIZE (_SS_MAXSIZE - (sizeof (sa_family_t)+
_SS_PAD1SIZE + _SS_ALIGNSIZE))
struct sockaddr_storage {
uint8_t __ss_len; /* address length */
sa_family_t __ss_family; /* address family */
/* Following fields are implementation specific */
char __ss_pad1[_SS_PAD1SIZE];
/* 6 byte pad, this is to make implementation
/* specific pad up to alignment field that */
/* follows explicit in the data structure */
int64_t __ss_align; /* field to force desired structure */
/* storage alignment */
char __ss_pad2[_SS_PAD2SIZE];
/* 112 byte pad to achieve desired size, */
/* _SS_MAXSIZE value minus size of ss_len, */
/* __ss_family, __ss_pad1, __ss_align fields is 112 */
};
This example aligns on a 64 bit boundary π The implementation specific field __ss_align, along with __ss_pad1, forces 64-bit alignment, which is good enough for the needs of sockaddr_in6 (IPv6) and sockaddr_in (IPv4) address data structures. The size of the padding field __ss_pad1 depends on the chosen alignment boundary. The size of the padding field __ss_pad2 depends on the overall size chosen for the structure. In the example above, this size and alignment are represented by implementation specific (not required) constants _SS_MAXSIZE (chosen value 128) and _SS_ALIGNMENT (with chosen value 8). The constants _SS_PAD1SIZE (derived value 6) and _SS_PAD2SIZE (derived value 112) are also just for illustration and not required. The implementation specific definitions and structure field names above start with an underscore to denote the implementation private namespace. Portable code is not expected to access or reference those fields or constants.
The sockaddr_storage structure solves the problem of declaring storage for automatic variables that is large enough and aligned enough to store a socket address data structure of any family β¨ For example, code that has a file descriptor but no context of the address family can pass a pointer to a variable of this type wherever a pointer to a socket address structure is expected, such as in calls to getpeername(), and then figure out the address family by looking at the received content after the call.
The sockaddr_storage structure may also be useful with certain other interfaces that need a generic socket address large enough and aligned for use with multiple address families. A discussion of those interfaces is outside the scope of this document.
Also, a lot of existing code assumes that any socket address structure can fit in a generic sockaddr structure. That has been true for IPv4 socket address structures, and it has always been false for Unix domain socket address structures (but in practice this hasn't been a problem). It's also false for IPv6 socket address structures, and that can be a problem π¬
So now an application can do the following:
struct sockaddr_storage __ss;
struct sockaddr_in6 *sin6;
sin6 = (struct sockaddr_in6 *) &__ss;
4. Interface Identification β¨
This API uses an interface index (a small positive integer) to identify the local interface on which a multicast group is joined (Section 5.3). Additionally, the advanced API [4] uses these same interface indexes to identify the interface on which a datagram is received, or to specify the interface on which a datagram is to be sent π¦
Interfaces are normally known by names like "le0", "sl1", "ppp2", and the like. On Berkeley-derived implementations, when an interface is made known to the system, the kernel assigns a unique positive integer value (called the interface index) to that interface. These are small positive integers that start at 1. (Note that 0 is never used for an interface index.) There may be gaps, so there may be no current interface for a particular positive interface index πΈ
This API defines two functions that map between an interface name and index, a third function that returns all the interface names and indexes, and a fourth function that returns the dynamic memory allocated by the previous function. How these functions are implemented is left up to the implementation. 4.4BSD implementations can implement these functions using the existing sysctl() function with the NET_RT_IFLIST command. Other implementations may wish to use ioctl() for this purpose π
4.1 Name-to-Index π
Okay so the first function takes an interface name and gives you back its index. Super useful, bestie. π
#include <net/if.h>
unsigned int if_nametoindex(const char *ifname);
If the interface name you passed in doesn't exist, the return value is 0 and errno is set to ENXIO. π If something goes wrong on the system side, like running out of memory, the return value is also 0, but errno gets set to the proper value (for example, ENOMEM). Main character error handling, honestly. π
4.2 Index-to-Name π¦
The second function does the reverse. It takes an interface index and maps it back to its name. β¨
#include <net/if.h>
char *if_indextoname(unsigned int ifindex, char *ifname);
The ifname argument must point to a buffer of at least IF_NAMESIZE bytes. The interface name that matches the index you gave gets written into that buffer. (IF_NAMESIZE is also defined in <net/if.h>, and its value includes a terminating null byte at the end of the interface name, so don't skimp on the size, babe. π) This same pointer is also what the function returns. πΈ
If there's no interface that matches the index, you get NULL back and errno is set to ENXIO. If there's a system error instead (like running out of memory), if_indextoname returns NULL and errno would be set to the proper value (for example, ENOMEM). Two different ways to get a NULL, same energy. π
4.3 Return All Interface Names and Indexes π§
The if_nameindex structure holds the info about a single interface. You get it by including the <net/if.h> header, and it looks like this:
struct if_nameindex {
unsigned int if_index; /* 1, 2, ... */
char *if_name; /* null terminated name: "le0", ... */
};
The last function returns an array of if_nameindex structures, with one structure for each interface. It's giving "list everything" vibes. π
struct if_nameindex *if_nameindex(void);
The end of the array is marked by a structure with an if_index of 0 and an if_name of NULL. So you know when to stop. If there's an error, the function returns a NULL pointer and sets errno to the appropriate value. π«Ά
Heads up: the memory for this array, plus the interface names pointed to by the if_name members, gets allocated dynamically. That memory is freed by the next function, so don't forget about it! π¨
4.4 Free Memory π§Ή
The following function frees the dynamic memory that was allocated by if_nameindex(). Clean up after yourself, periodt. β¨
#include <net/if.h>
void if_freenameindex(struct if_nameindex *ptr);
The argument to this function must be a pointer that was returned by if_nameindex(). No freeing random pointers, no cap. π
ββοΈ
Currently net/if.h doesn't have prototype definitions for functions, and it is recommended that these definitions be defined in net/if.h as well as the struct if_nameindex{}. Ngl, this is a little bit of a loose end, but it's noted. π
5. Socket Options β¨
Okay bestie, a bunch of brand new socket options are defined for IPv6. π All of these new options live at the IPPROTO_IPV6 level. That means the "level" parameter in the getsockopt() and setsockopt() calls is IPPROTO_IPV6 whenever you use these options. Every new option name starts with the prefix IPV6_, which makes it super clear that they apply to IPv6. It's iconic, honestly. π¦
The declaration for IPPROTO_IPV6, the new IPv6 socket options, and the related constants in this section come from including the <netinet/in.h> header. π
5.1 Unicast Hop Limit πΈ
A new setsockopt() option controls the hop limit used in outgoing unicast IPv6 packets. The name of this option is IPV6_UNICAST_HOPS, and it's used at the IPPROTO_IPV6 layer. Here's how it looks in action:
int hoplimit = 10;
if (setsockopt(s, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
(char *) &hoplimit, sizeof(hoplimit)) == -1)
perror("setsockopt IPV6_UNICAST_HOPS");
When you set IPV6_UNICAST_HOPS with setsockopt(), the value you give is used as the hop limit for all subsequent unicast packets sent through that socket. If you don't set it, the system picks a default value for you. π
The integer hop limit value (called x) is interpreted like this:
x < -1: return an error of EINVAL
x == -1: use kernel default
0 <= x <= 255: use x
x >= 256: return an error of EINVAL
You can use IPV6_UNICAST_HOPS with getsockopt() to check what hop limit the system will use for subsequent unicast packets sent through that socket. Like this:
int hoplimit;
size_t len = sizeof(hoplimit);
if (getsockopt(s, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
(char *) &hoplimit, &len) == -1)
perror("getsockopt IPV6_UNICAST_HOPS");
else
printf("Using %d for hop limit.\n", hoplimit);
5.2 Sending and Receiving Multicast Packets π‘
IPv6 apps can send UDP multicast packets by simply putting an IPv6 multicast address in the address argument of the sendto() function. Easy peasy. π
There are three socket options at the IPPROTO_IPV6 layer that control some of the parameters for sending multicast packets. Setting these options is not required: apps can send multicast packets without touching them at all. π§ The setsockopt() options for controlling the sending of multicast packets are summarized below, and these three options can also be used with getsockopt().
IPV6_MULTICAST_IF
Sets the interface to use for outgoing multicast packets. The argument is the index of the interface to use.
Argument type: unsigned int
IPV6_MULTICAST_HOPS
Sets the hop limit to use for outgoing multicast packets. (Side note: a separate option, IPV6_UNICAST_HOPS, is for setting the hop limit on outgoing unicast packets. Two different vibes! π)
The argument is interpreted the same way as for the IPV6_UNICAST_HOPS option:
x < -1: return an error of EINVAL
x == -1: use kernel default
0 <= x <= 255: use x
x >= 256: return an error of EINVAL
If IPV6_MULTICAST_HOPS is not set, the default is 1 (same as IPv4 today). π
Argument type: int
IPV6_MULTICAST_LOOP
If a multicast datagram is sent to a group that the sending host itself belongs to (on the outgoing interface), a copy of the datagram is looped back by the IP layer for local delivery, but only if this option is set to 1. If this option is set to 0, a copy is not looped back. Any other option values return an error of EINVAL. π
If IPV6_MULTICAST_LOOP is not set, the default is 1 (loopback, same as IPv4 today). β¨
Argument type: unsigned int
The reception of multicast packets is controlled by the two setsockopt() options summarized below. If you try to use these two options with getsockopt(), you get an error of EOPNOTSUPP. Not it. π
IPV6_JOIN_GROUP
Joins a multicast group on a specified local interface. If the interface index is specified as 0, the kernel chooses the local interface. For example, some kernels look up the multicast group in the normal IPv6 routing table and use the resulting interface. πΊοΈ
Argument type: struct ipv6_mreq
IPV6_LEAVE_GROUP
Leaves a multicast group on a specified interface. Bye bye, group chat. π
Argument type: struct ipv6_mreq
The argument type for both of these options is the ipv6_mreq structure, which is defined by including the <netinet/in.h> header:
struct ipv6_mreq {
struct in6_addr ipv6mr_multiaddr; /* IPv6 multicast addr */
unsigned int ipv6mr_interface; /* interface index */
};
Note that to receive multicast datagrams, a process must join the multicast group and bind the UDP port that the datagrams will be sent to. Some processes also bind the multicast group address to the socket, in addition to the port. That way, other datagrams destined for that same port don't get delivered to the socket. Protective girlfriend behavior. π‘οΈπ«Ά
6. Library Functions π
Brand new library functions are needed to do a variety of operations with IPv6 addresses. Functions are needed to look up IPv6 addresses in the Domain Name System (DNS). Both forward lookup (nodename-to-address translation) and reverse lookup (address-to-nodename translation) need to be supported. Functions are also needed to convert IPv6 addresses between their binary and textual forms. π
We note that the two existing functions, gethostbyname() and gethostbyaddr(), are left as-is. New functions are defined to handle both IPv4 and IPv6 addresses. Old friends stay, new friends join. π₯Ήπ
6.1 Nodename-to-Address Translation
okay so gethostbyname() is lowkey not it anymore π
. It gives you no way to say what kinds of addresses you want (IPv4 only, IPv6 only, IPv4-mapped IPv6 is OK, etc.), and a lot of implementations of it aren't thread safe π. RFC 2133 defined gethostbyname2(), but that one was messy too. You had to set a global option (RES_USE_INET6) when you needed IPv6 addresses, and you also needed a flag argument for more control over which address types you get back π« .
The following function is new and must be thread safe β¨:
#include <sys/socket.h>
#include <netdb.h>
struct hostent *getipnodebyname(const char *name, int af, int flags
int *error_num);
The name argument can be either a node name or a numeric address string (so a dotted-decimal IPv4 address or an IPv6 hex address) π. The af argument is the address family, either AF_INET or AF_INET6. The error_num value comes back to the caller through a pointer, with the right error code in error_num, so error handling stays thread safe π§. error_num gets set to one of these values:
HOST_NOT_FOUND: No such host is known.NO_ADDRESS: The server recognised the request and the name, but no address is available. Another type of request to the name server for the domain might return an answer.NO_RECOVERY: An unexpected server failure occurred which cannot be recovered.TRY_AGAIN: A temporary and possibly transient error occurred, such as a failure of a server to respond.
The flags argument specifies the types of addresses that get searched for and the types that get returned π¦. Fyi, a special flags value of AI_DEFAULT (defined below) should handle most applications π.
So porting a simple app to IPv6 is basically this swap:
hptr = gethostbyname(name);
becomes:
hptr = getipnodebyname(name, AF_INET6, AI_DEFAULT, &error_num);
Then you change any error handling code to read error_num instead of externally declared variables, like h_errno πΈ.
Apps that want finer control over which addresses get searched for and returned can pass other combinations in the flags argument π.
A flags of 0 means a strict reading of the af argument:
- If
flagsis 0 andafisAF_INET, then the caller wants only IPv4 addresses. A query is made for A records. If it works, the IPv4 addresses come back and theh_lengthmember of thehostentstructure will be 4. Otherwise the function returns a NULL pointer. - If
flagsis 0 andafisAF_INET6, then the caller wants only IPv6 addresses. A query is made for AAAA records. If it works, the IPv6 addresses come back and theh_lengthmember of thehostentstructure will be 16. Otherwise the function returns a NULL pointer.
Other constants can be logically-ORed into the flags argument to change how the function behaves π.
- If the
AI_V4MAPPEDflag is specified along with anafofAF_INET6, then the caller will accept IPv4-mapped IPv6 addresses. That means if no AAAA records are found, a query is made for A records, and any that get found come back as IPv4-mapped IPv6 addresses (h_lengthwill be 16). TheAI_V4MAPPEDflag is ignored unlessafequalsAF_INET6. - The
AI_ALLflag is used together with theAI_V4MAPPEDflag, and it's only used with the IPv6 address family. WhenAI_ALLis logically or'd with theAI_V4MAPPEDflag, the caller wants all addresses: IPv6 and IPv4-mapped IPv6. A query is made for AAAA records first, and if it works, the IPv6 addresses come back. Then another query is made for A records, and any found come back as IPv4-mapped IPv6 addresses.h_lengthwill be 16. Only if both queries fail does the function return a NULL pointer. This flag is ignored unlessafequalsAF_INET6π. - The
AI_ADDRCONFIGflag says a query for AAAA records should only happen if the node has at least one IPv6 source address configured, and a query for A records should only happen if the node has at least one IPv4 source address configured.
For example, say the node has no IPv6 source addresses configured, af equals AF_INET6, and the node name being looked up has both AAAA and A records. Then:
- (a) if only
AI_ADDRCONFIGis specified, the function returns a NULL pointer; - (b) if
AI_ADDRCONFIG | AI_V4MAPPEDis specified, the A records are returned as IPv4-mapped IPv6 addresses;
The special flags value of AI_DEFAULT is defined as:
#define AI_DEFAULT (AI_V4MAPPED | AI_ADDRCONFIG)
We noted that getipnodebyname() must allow the name argument to be either a node name or a literal address string (so a dotted-decimal IPv4 address or an IPv6 hex address) π. That saves apps from having to call inet_pton() just to handle literal address strings.
There are four scenarios, based on the type of literal address string and the value of the af argument β.
The two simple cases are:
When name is a dotted-decimal IPv4 address and af equals AF_INET, or when name is an IPv6 hex address and af equals AF_INET6. The members of the returned hostent structure are: h_name points to a copy of the name argument, h_aliases is a NULL pointer, h_addrtype is a copy of the af argument, h_length is either 4 (for AF_INET) or 16 (for AF_INET6), h_addr_list[0] is a pointer to the 4-byte or 16-byte binary address, and h_addr_list[1] is a NULL pointer.
Whennameis a dotted-decimal IPv4 address andafequalsAF_INET6, andflagsequalsAI_V4MAPPED, an IPv4-mapped IPv6 address is returned:h_namepoints to an IPv6 hex address containing the IPv4-mapped IPv6 address,h_aliasesis a NULL pointer,h_addrtypeisAF_INET6,h_lengthis 16,h_addr_list[0]is a pointer to the 16-byte binary address, andh_addr_list[1]is a NULL pointer. IfAI_V4MAPPEDis set (with or withoutAI_ALL), return IPv4-mapped; otherwise return NULL.
It is an error when name is an IPv6 hex address and af equals AF_INET. The function's return value is a NULL pointer and error_num equals HOST_NOT_FOUND π.
6.2 Address-To-Nodename Translation
The following function has the same arguments as the existing gethostbyaddr() function, but it adds an error number π§.
#include <sys/socket.h> #include <netdb.h>
struct hostent *getipnodebyaddr(const void *src, size_t len,
int af, int *error_num);
As with getipnodebyname(), getipnodebyaddr() must be thread safe β¨. The error_num value is returned to the caller with the appropriate error code, so error handling stays thread safe. These error conditions may be returned for error_num:
HOST_NOT_FOUND: No such host is known.NO_ADDRESS: The server recognized the request and the name, but no address is available. Another type of request to the name server for the domain might return an answer.NO_RECOVERY: An unexpected server failure occurred which cannot be recovered.TRY_AGAIN: A temporary and possibly transient error occurred, such as a failure of a server to respond.
One possible source of confusion is how IPv4-mapped IPv6 addresses and IPv4-compatible IPv6 addresses get handled, but the following logic should apply π:
- If
afisAF_INET6, and iflenequals 16, and if the IPv6 address is an IPv4-mapped IPv6 address or an IPv4-compatible IPv6 address, then skip over the first 12 bytes of the IPv6 address, setaftoAF_INET, and setlento 4. - If
afisAF_INET, look up the name for the given IPv4 address (e.g., query for a PTR record in the in-addr.arpa domain). - If
afisAF_INET6, look up the name for the given IPv6 address (e.g., query for a PTR record in the ip6.int domain). - If the function is returning success, then the single address that is returned in the
hostentstructure is a copy of the first argument to the function, with the same address family that was passed as an argument to this function.
All four steps listed are performed, in order π. Also note that the IPv6 hex addresses "::" and "::1" MUST NOT be treated as IPv4-compatible addresses, and if the address is "::", HOST_NOT_FOUND MUST be returned and a query of the address not performed π.
Also, for the macro in section 6.7, IN6_IS_ADDR_V4COMPAT MUST return false for "::" and "::1" π«Ά.
6.3 Freeing memory for getipnodebyname and getipnodebyaddr
The hostent structure does not change from its existing definition π¦. This structure, and the information pointed to by this structure, are dynamically allocated by getipnodebyname and getipnodebyaddr. The following function frees this memory:
#include <netdb.h>
void freehostent(struct hostent *ptr);
6.4. Protocol-Independent Nodename and Service Name Translation β¨
Okay so nodename-to-address translation is done in a protocol-independent way, using the getaddrinfo() function. It's taken from the IEEE POSIX 1003.1g (Protocol Independent Interfaces) draft spec [3]. π
The official spec for this function will be the final POSIX standard, with these extra requirements π:
getaddrinfo()(along with thegetnameinfo()function we cover in the next section) must be thread safe. π§΅- The
AI_NUMERICHOSTis new with this document. π - All fields in socket address structures returned by
getaddrinfo()that aren't filled in through an explicit argument (e.g.,sin6_flowinfoandsin_zero) must be set to 0. (This makes it way easier to compare socket address structures.) π§Ή getaddrinfo()must fill in the length field of a socket address structure (e.g.,sin6_len) on systems that support this field. π
We're writing our own independent description because POSIX standards aren't freely available the way IETF documents are, and that's just sad π
#include <sys/socket.h>
#include <netdb.h>
int getaddrinfo(const char *nodename, const char *servname,
const struct addrinfo *hints,
struct addrinfo **res);
The addrinfo structure is defined as a result of including the <netdb.h> header. Here's what it looks like:
struct addrinfo {
int ai_flags; /* AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST */
int ai_family; /* PF_xxx */
int ai_socktype; /* SOCK_xxx */
int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */
size_t ai_addrlen; /* length of ai_addr */
char *ai_canonname; /* canonical name for nodename */
struct sockaddr *ai_addr; /* binary address */
struct addrinfo *ai_next; /* next structure in linked list */
};
The function returns 0 when it succeeds, or a nonzero error code when it doesn't. These are the nonzero error codes from getaddrinfo(), all defined in <netdb.h> π¨:
EAI_ADDRFAMILY address family for nodename not supported
EAI_AGAIN temporary failure in name resolution
EAI_BADFLAGS invalid value for ai_flags
EAI_FAIL non-recoverable failure in name resolution
EAI_FAMILY ai_family not supported
EAI_MEMORY memory allocation failure
EAI_NODATA no address associated with nodename
EAI_NONAME nodename nor servname provided, or not known
EAI_SERVICE servname not supported for ai_socktype
EAI_SOCKTYPE ai_socktype not supported
EAI_SYSTEM system error returned in errno
The nodename and servname arguments are pointers to null-terminated strings, or NULL. One or both of them must be a non-NULL pointer. π In the normal client scenario, you specify both the nodename and the servname. In the normal server scenario, you only specify the servname. A non-NULL nodename string can be either a node name or a numeric host address string (a dotted-decimal IPv4 address or an IPv6 hex address). A non-NULL servname string can be either a service name or a decimal port number.
The caller can optionally pass an addrinfo structure, pointed to by the third argument, to give hints about the type of socket the caller supports. In this hints structure, every member other than ai_flags, ai_family, ai_socktype, and ai_protocol must be zero or a NULL pointer. π§ A value of PF_UNSPEC for ai_family means the caller will accept any protocol family. A value of 0 for ai_socktype means the caller will accept any socket type. A value of 0 for ai_protocol means the caller will accept any protocol.
For example, if the caller only handles TCP and not UDP, the ai_socktype member of the hints structure should be set to SOCK_STREAM when getaddrinfo() is called. If the caller only handles IPv4 and not IPv6, the ai_family member should be set to PF_INET instead. And if the third argument is a NULL pointer, it's the same as if the caller had filled in a zeroed addrinfo structure with ai_family set to PF_UNSPEC. Iconic, right? π¦
Upon successful return, a pointer to a linked list of one or more addrinfo structures comes back through the final argument. The caller can work through each addrinfo structure in this list by following the ai_next pointer until it hits a NULL pointer. In each returned addrinfo structure, the three members ai_family, ai_socktype, and ai_protocol are the matching arguments for a call to the socket() function. And in each one, the ai_addr member points to a filled-in socket address structure whose length is given by the ai_addrlen member. π
If the AI_PASSIVE bit is set in the ai_flags member of the hints structure, the caller plans to use the returned socket address structure in a call to bind(). In this case, if the nodename argument is a NULL pointer, the IP address portion of the socket address structure will be set to INADDR_ANY for an IPv4 address or IN6ADDR_ANY_INIT for an IPv6 address.
If the AI_PASSIVE bit is not set in the ai_flags member of the hints structure, the returned socket address structure will be ready for a call to connect() (for a connection-oriented protocol), or for either connect(), sendto(), or sendmsg() (for a connectionless protocol). In this case, if the nodename argument is a NULL pointer, the IP address portion of the socket address structure will be set to the loopback address. π
If the AI_CANONNAME bit is set in the ai_flags member of the hints structure, then after a successful return, the ai_canonname member of the first addrinfo structure in the linked list will point to a null-terminated string containing the canonical name of the specified nodename. π
If the AI_NUMERICHOST bit is set in the ai_flags member of the hints structure, a non-NULL nodename string must be a numeric host address string. Otherwise, an error of EAI_NONAME is returned. This flag stops any type of name resolution service (e.g., the DNS) from getting called. π«
All of the information returned by getaddrinfo() is dynamically allocated: the addrinfo structures, plus the socket address structures and canonical node name strings that the addrinfo structures point to. To give this information back to the system, you call freeaddrinfo():
#include <sys/socket.h> #include <netdb.h>
void freeaddrinfo(struct addrinfo *ai);
The addrinfo structure pointed to by the ai argument is freed, along with any dynamic storage it points to. This keeps going until a NULL ai_next pointer is encountered. π§Ή
To help applications print error messages based on the EAI_xxx codes returned by getaddrinfo(), this function is defined:
#include <sys/socket.h> #include <netdb.h>
char *gai_strerror(int ecode);
The argument is one of the EAI_xxx values defined earlier, and the return value points to a string describing the error. If the argument isn't one of the EAI_xxx values, the function still returns a pointer to a string whose contents indicate an unknown error. π€·ββοΈ
6.5. Socket Address Structure to Nodename and Service Name π
POSIX 1003.1g doesn't include a function that does the reverse of getaddrinfo(), meaning one that looks up a nodename and service name from a binary address and port. π So we define this one:
#include <sys/socket.h>
#include <netdb.h>
int getnameinfo(const struct sockaddr *sa, socklen_t salen,
char *host, size_t hostlen,
char *serv, size_t servlen,
int flags);
This function looks up an IP address and port number the caller provides, in the DNS and the system-specific databases. It returns text strings for both, in buffers the caller provides. It signals success with a zero return value, and a non-zero return value means failure. π
The first argument, sa, points to either a sockaddr_in structure (for IPv4) or a sockaddr_in6 structure (for IPv6), which holds the IP address and port number. The salen argument gives the length of that sockaddr_in or sockaddr_in6 structure.
The function returns the nodename associated with the IP address in the buffer pointed to by the host argument. The caller gives the size of this buffer through the hostlen argument. The service name associated with the port number is returned in the buffer pointed to by serv, and the servlen argument gives the length of that buffer. The caller can say not to return either string by passing a zero value for hostlen or servlen. Otherwise, the caller must provide buffers that are big enough to hold the nodename and the service name, including the terminating null characters. π¦
Unfortunately, most systems don't provide constants that specify the maximum size of either a fully-qualified domain name or a service name. π© So to help the application size the buffers for these two returned strings, the following constants are defined in <netdb.h>:
#define NI_MAXHOST 1025
#define NI_MAXSERV 32
The first value is actually defined as the constant MAXDNAME in recent versions of BIND's <arpa/nameser.h> header (older versions of BIND define this constant to be 256). The second is a guess based on the services listed in the current Assigned Numbers RFC. π€
The final argument is a flag that changes the default behaviour of this function. By default, the fully-qualified domain name (FQDN) for the host is looked up in the DNS and returned. If the flag bit NI_NOFQDN is set, only the nodename portion of the FQDN is returned for local hosts. βοΈ
If the flag bit NI_NUMERICHOST is set, or if the host's name can't be located in the DNS, the numeric form of the host's address is returned instead of its name (e.g., by calling inet_ntop() instead of getipnodebyaddr()). If the flag bit NI_NAMEREQD is set, an error is returned when the host's name can't be located in the DNS. π
ββοΈ
If the flag bit NI_NUMERICSERV is set, the numeric form of the service address (e.g., its port number) is returned instead of its name. The two NI_NUMERICxxx flags are required to support the "-n" flag that lots of commands provide. π’
A fifth flag bit, NI_DGRAM, specifies that the service is a datagram service. It causes getservbyport() to be called with a second argument of "udp" instead of its default of "tcp". This is required for the few ports (e.g. 512-514) that have different services for UDP and TCP. π¦
These NI_xxx flags are defined in <netdb.h> along with the AI_xxx flags already defined for getaddrinfo(). π
6.6 Address Conversion Functions
okay so inet_addr() and inet_ntoa() handle IPv4 binary <-> text, but IPv6 apps need their own glow-up β¨ so these two functions do both IPv6 and IPv4 π
#include <sys/socket.h>
#include <arpa/inet.h>
int inet_pton(int af, const char *src, void *dst);
const char *inet_ntop(int af, const void *src,
char *dst, size_t size);
inet_pton() takes an address in its normal text form and turns it into the numeric binary form π§ the af argument tells it which family the address belongs to, and right now AF_INET and AF_INET6 are the ones supported. src points at the string you're passing in, and dst points at a buffer where the numeric address gets stored. The address comes back in network byte order πΈ inet_pton() returns 1 if the conversion works, 0 if the input isn't a valid IPv4 dotted-decimal string or a valid IPv6 address string, or -1 with errno set to EAFNOSUPPORT if af is unknown. the calling application has to make sure the buffer dst points to is big enough for the numeric address (4 bytes for AF_INET, 16 bytes for AF_INET6) π«Ά
If af is AF_INET, the function accepts a string in the standard IPv4 dotted-decimal form:
ddd.ddd.ddd.ddd
where ddd is a one to three digit decimal number between 0 and 255. ngl this is the part I'd tattoo on my brain π many implementations of the existing inet_addr() and inet_aton() functions accept nonstandard input: octal numbers, hexadecimal numbers, and fewer than four numbers. inet_pton() does not accept these formats π
If af is AF_INET6, the function accepts a string in one of the standard IPv6 text forms defined in Section 2.2 of the addressing architecture specification [2]. π¦
inet_ntop() goes the other way, turning a numeric address into a text string that's suitable for presentation β¨ af says what family it is, and this can be AF_INET or AF_INET6. src points to a buffer holding an IPv4 address if af is AF_INET, or an IPv6 address if af is AF_INET6, and the address must be in network byte order. dst points to a buffer where the resulting text string gets stored, and size tells the function how big that buffer is. The application must specify a non-NULL dst argument π For IPv6 addresses, the buffer must be at least 46-octets. For IPv4 addresses, the buffer must be at least 16-octets. To make life easier when declaring buffers for IPv4 and IPv6 strings, the following two constants are defined in <netinet/in.h>:
#define INET_ADDRSTRLEN 16
#define INET6_ADDRSTRLEN 46
inet_ntop() returns a pointer to the buffer holding the text string if the conversion succeeds, and NULL otherwise. If it fails, errno is set to EAFNOSUPPORT if af is invalid, or ENOSPC if the size of the result buffer is inadequate π
6.7 Address Testing Macros
these macros let you test for special IPv6 addresses π
#include <netinet/in.h>
int IN6_IS_ADDR_UNSPECIFIED (const struct in6_addr *);
int IN6_IS_ADDR_LOOPBACK (const struct in6_addr *);
int IN6_IS_ADDR_MULTICAST (const struct in6_addr *);
int IN6_IS_ADDR_LINKLOCAL (const struct in6_addr *);
int IN6_IS_ADDR_SITELOCAL (const struct in6_addr *);
int IN6_IS_ADDR_V4MAPPED (const struct in6_addr *);
int IN6_IS_ADDR_V4COMPAT (const struct in6_addr *);
int IN6_IS_ADDR_MC_NODELOCAL(const struct in6_addr *);
int IN6_IS_ADDR_MC_LINKLOCAL(const struct in6_addr *);
int IN6_IS_ADDR_MC_SITELOCAL(const struct in6_addr *);
int IN6_IS_ADDR_MC_ORGLOCAL (const struct in6_addr *);
int IN6_IS_ADDR_MC_GLOBAL (const struct in6_addr *);
The first seven macros return true if the address is of the specified type, or false otherwise π The last five test the scope of a multicast address. They return true if the address is a multicast address of the specified scope, or false if it's either not a multicast address or not of that scope π Note that IN6_IS_ADDR_LINKLOCAL and IN6_IS_ADDR_SITELOCAL return true only for the two local-use IPv6 unicast addresses. These two macros do not return true for IPv6 multicast addresses of either link-local scope or site-local scope. > not me mixing up unicast and multicast scopes again π
7. Summary of New Definitions
okay this is the cheat sheet πβ¨ the constants, structure, and extern definitions from this memo, sorted by header:
<net/if.h> IF_NAMESIZE
<net/if.h> struct if_nameindex{};
<netdb.h> AI_ADDRCONFIG
<netdb.h> AI_DEFAULT
<netdb.h> AI_ALL
<netdb.h> AI_CANONNAME
<netdb.h> AI_NUMERICHOST
<netdb.h> AI_PASSIVE
<netdb.h> AI_V4MAPPED
<netdb.h> EAI_ADDRFAMILY
<netdb.h> EAI_AGAIN
<netdb.h> EAI_BADFLAGS
<netdb.h> EAI_FAIL
<netdb.h> EAI_FAMILY
<netdb.h> EAI_MEMORY
<netdb.h> EAI_NODATA
<netdb.h> EAI_NONAME
<netdb.h> EAI_SERVICE
<netdb.h> EAI_SOCKTYPE
<netdb.h> EAI_SYSTEM
<netdb.h> NI_DGRAM
<netdb.h> NI_MAXHOST
<netdb.h> NI_MAXSERV
<netdb.h> NI_NAMEREQD
<netdb.h> NI_NOFQDN
<netdb.h> NI_NUMERICHOST
<netdb.h> NI_NUMERICSERV
<netdb.h> struct addrinfo{};
<netinet/in.h> IN6ADDR_ANY_INIT
<netinet/in.h> IN6ADDR_LOOPBACK_INIT
<netinet/in.h> INET6_ADDRSTRLEN
<netinet/in.h> INET_ADDRSTRLEN
<netinet/in.h> IPPROTO_IPV6
<netinet/in.h> IPV6_JOIN_GROUP
<netinet/in.h> IPV6_LEAVE_GROUP
<netinet/in.h> IPV6_MULTICAST_HOPS
<netinet/in.h> IPV6_MULTICAST_IF
<netinet/in.h> IPV6_MULTICAST_LOOP
<netinet/in.h> IPV6_UNICAST_HOPS
<netinet/in.h> SIN6_LEN
<netinet/in.h> extern const struct in6_addr in6addr_any;
<netinet/in.h> extern const struct in6_addr in6addr_loopback;
<netinet/in.h> struct in6_addr{};
<netinet/in.h> struct ipv6_mreq{};
<netinet/in.h> struct sockaddr_in6{};
<sys/socket.h> AF_INET6
<sys/socket.h> PF_INET6
<sys/socket.h> struct sockaddr_storage;
and here are the function and macro prototypes from this memo, also sorted by header π
<arpa/inet.h> int inet_pton(int, const char *, void *);
<arpa/inet.h> const char *inet_ntop(int, const void *,
char *, size_t);
<net/if.h> char *if_indextoname(unsigned int, char *);
<net/if.h> unsigned int if_nametoindex(const char *);
<net/if.h> void if_freenameindex(struct if_nameindex *);
<net/if.h> struct if_nameindex *if_nameindex(void);
<netdb.h> int getaddrinfo(const char *, const char *,
const struct addrinfo *,
struct addrinfo **);
<netdb.h> int getnameinfo(const struct sockaddr *, socklen_t,
char *, size_t, char *, size_t, int);
<netdb.h> void freeaddrinfo(struct addrinfo *);
<netdb.h> char *gai_strerror(int);
<netdb.h> struct hostent *getipnodebyname(const char *, int, int,
int *);
<netdb.h> struct hostent *getipnodebyaddr(const void *, size_t,
int, int *);
<netdb.h> void freehostent(struct hostent *);
<netinet/in.h> int IN6_IS_ADDR_LINKLOCAL(const struct in6_addr *);
<netinet/in.h> int IN6_IS_ADDR_LOOPBACK(const struct in6_addr *);
<netinet/in.h> int IN6_IS_ADDR_MC_GLOBAL(const struct in6_addr *);
<netinet/in.h> int IN6_IS_ADDR_MC_LINKLOCAL(const struct in6_addr *);
<netinet/in.h> int IN6_IS_ADDR_MC_NODELOCAL(const struct in6_addr *);
<netinet/in.h> int IN6_IS_ADDR_MC_ORGLOCAL(const struct in6_addr *);
<netinet/in.h> int IN6_IS_ADDR_MC_SITELOCAL(const struct in6_addr *);
<netinet/in.h> int IN6_IS_ADDR_MULTICAST(const struct in6_addr *);
<netinet/in.h> int IN6_IS_ADDR_SITELOCAL(const struct in6_addr *);
<netinet/in.h> int IN6_IS_ADDR_UNSPECIFIED(const struct in6_addr *);
<netinet/in.h> int IN6_IS_ADDR_V4COMPAT(const struct in6_addr *);
<netinet/in.h> int IN6_IS_ADDR_V4MAPPED(const struct in6_addr *);
8. Security Considerations
π¨ okay this part is serious, bestie π IPv6 brings a bunch of new security mechanisms, and a lot of them need to be reachable from applications. Companion memos that detail the extensions to the socket interfaces for IPv6 security are being written.
9. Year 2000 Considerations
good news π there are no Year 2000 issues for this memo when it comes to the use of dates π β¨
Changes From RFC 2133 π
okay so bestie, this is the changelog bit where the authors spill every edit they made. it's giving receipts π§Ύπ
Changes made in the March 1998 Edition (-01 draft) πΈ
- Changed all "hostname" to "nodename" for consistency with other IPv6 documents. β¨
- Section 3.3: changed the comment for
sin6_flowinfoto be "traffic class & flow info" and updated the matching text description to the current definition of these two fields. π¦ - Section 3.10 ("Portability Additions") is new. π§
- Section 6: a new paragraph was added reiterating that the existing
gethostbyname()andgethostbyaddr()are not changed. π - Section 6.1: changed
gethostbyname3()togetnodebyname(). AddedAI_DEFAULTto handle the majority of applications. RenamedAI_V6ADDRCONFIGtoAI_ADDRCONFIGand defined it for A records and IPv4 addresses too. Defined exactly whatgetnodebyname()must return if the name argument is a numeric address string. π₯ - Section 6.2: changed
gethostbyaddr()togetnodebyaddr(). Reworded items 2 and 3 in the description of how to handle IPv4-mapped and IPv4-compatible addresses to "lookup a name" for a given address, instead of specifying what type of DNS query to issue. π - Section 6.3: added two more requirements to
getaddrinfo(). β - Section 7: added the following constants to the list for
<netdb.h>:AI_ADDRCONFIG,AI_ALL, andAI_V4MAPPED. Addedunion sockaddr_unionandSA_LENto the lists for<sys/socket.h>. π - Updated references. π
Changes made in the November 1997 Edition (-00 draft) π·
- The data types have been changed to conform with Draft 6.6 of the Posix 1003.1g standard. π
- Section 3.2: data type of
s6_addrchanged touint8_t. π - Section 3.3: data type of
sin6_familychanged tosa_family_t. Data type ofsin6_portchanged toin_port_t. Data type ofsin6_flowinfochanged touint32_t. β¨ - Section 3.4: same as Section 3.3, plus the data type of
sin6_lenchanged touint8_t. π¦ - Section 6.2: first argument of
gethostbyaddr()changed fromconst char *toconst void *, and second argument changed frominttosize_t. π§ - Section 6.4: second argument of
getnameinfo()changed fromsize_ttosocklen_t. π - The wording was changed when new structures were defined, to be more explicit about which header must be included to define the structure: Section 3.2 (
in6_addr{}), Section 3.3 (sockaddr_in6{}), Section 3.4 (sockaddr_in6{}), Section 4.3 (if_nameindex{}), Section 5.3 (ipv6_mreq{}), and Section 6.3 (addrinfo{}). π - Section 4:
NET_RT_LISTchanged toNET_RT_IFLIST. π«§ - Section 5.1: the
IPV6_ADDRFORMsocket option was removed. ποΈ - Section 5.3: added a note that an option value other than 0 or 1 for
IPV6_MULTICAST_LOOPreturns an error. Added a note thatIPV6_MULTICAST_IF,IPV6_MULTICAST_HOPS, andIPV6_MULTICAST_LOOPcan also be used withgetsockopt(), butIPV6_ADD_MEMBERSHIPandIPV6_DROP_MEMBERSHIPcannot be used withgetsockopt(). π - Section 6.1: removed the description of
gethostbyname2()and its associatedRES_USE_INET6option, replacing it withgethostbyname3(). π - Section 6.2: added the requirement that
gethostbyaddr()be thread safe. Reworded step 4 to avoid using theRES_USE_INET6option. π§΅ - Section 6.3: added the requirement that
getaddrinfo()andgetnameinfo()be thread safe. Added theAI_NUMERICHOSTflag. πΈ - Section 6.6: added clarification about the
IN6_IS_ADDR_LINKLOCALandIN6_IS_ADDR_SITELOCALmacros. π
Changes made to the draft -01 specification Sept 98 π
- Changed priority to traffic class in the spec. π«
- Added the need for scope identification in Section 2.1. π
- Added
sin6_scope_idtostruct sockaddr_in6in Sections 3.3 and 3.4. π§© - Changed Section 3.10 to use a generic storage structure to support holding IPv6 addresses, and removed the
SA_LENmacro. ποΈ - Distinguished between invalid input parameters and system failures for Interface Identification in Sections 4.1 and 4.2. π
- Added defaults for multicast operations in Section 5.2, and changed the names from ADD to JOIN and DROP to LEAVE to be consistent with IPv6 multicast terminology. πͺ
- Changed
getnodebynametogetipnodebyname,getnodebyaddrtogetipnodebyaddr, and added an MT safe error code to function parameters in Section 6. π§΅ - Moved
freehostentto its own subsection aftergetipnodebyaddr, now 6.3 (so this bumps all remaining sections in Section 6). π§ - Clarified the use of
AI_ALLandAI_V4MAPPED: these are dependent on the AF parameter and must be used as a conjunction in Section 6.1. π€ - Removed the restriction that literal addresses cannot be used with a flags argument in Section 6.1. π
- Added a Year 2000 Section to the draft. ποΈ
- Deleted a reference to the following, because the attached is deleted from the ID directory and has expired. But the logic from the aforementioned draft still applies, so that was kept in the Section 6.2 bullets after the 3rd paragraph:
- [7] P. Vixie, "Reverse Name Lookups of Encapsulated IPv4 Addresses in IPv6", Internet-Draft,
<draft-vixie-ipng-ipv4ptr-00.txt>, May 1996.
- [7] P. Vixie, "Reverse Name Lookups of Encapsulated IPv4 Addresses in IPv6", Internet-Draft,
- Deleted the following reference, as it is no longer referenced and the draft has expired:
- [3] D. McDonald, "A Simple IP Security API Extension to BSD Sockets", Internet-Draft,
<draft-mcdonald-simple-ipsec-api-01.txt>, March 1997.
- [3] D. McDonald, "A Simple IP Security API Extension to BSD Sockets", Internet-Draft,
- Deleted the following reference, as it is no longer referenced:
- [4] C. Metz, "Network Security API for Sockets", Internet-Draft,
<draft-metz-net-security-api-01.txt>, January 1998.
- [4] C. Metz, "Network Security API for Sockets", Internet-Draft,
- Updated current references to current status. π
- Added alignment notes for
in6_addrandsin6_addr. π - Clarified further that AI_V4MAPPED must be used with a dotted IPv4 literal address for
getipnodebyname()when the address family isAF_INET6. π§ - Added text to clarify
::and::1when used bygetipnodebyaddr(). π
Acknowledgments π«Ά
Thanks to the many people who made suggestions and provided feedback to this document, including: Werner Almesberger, Ran Atkinson, Fred Baker, Dave Borman, Andrew Cherenson, Alex Conta, Alan Cox, Steve Deering, Richard Draves, Francis Dupont, Robert Elz, Marc Hasson, Tom Herbert, Bob Hinden, Wan-Yen Hsu, Christian Huitema, Koji Imada, Markus Jork, Ron Lee, Alan Lloyd, Charles Lynn, Dan McDonald, Dave Mitton, Thomas Narten, Josh Osborne, Craig Partridge, Jean-Luc Richier, Erik Scoredos, Keith Sklower, Matt Thomas, Harvey Thompson, Dean D. Throop, Karen Tracey, Glenn Trewitt, Paul Vixie, David Waitzman, Carl Williams, and Kazu Yamamoto. π
The getaddrinfo() and getnameinfo() functions are taken from an earlier Internet Draft by Keith Sklower. As noted in that draft, William Durst, Steven Wise, Michael Karels, and Eric Allman provided many useful discussions on the subject of protocol-independent name-to-address translation, and reviewed early versions of Keith Sklower's original proposal. Eric Allman implemented the first prototype of getaddrinfo(). The observation that specifying the pair of name and service would suffice for connecting to a service independent of protocol details was made by Marshall Rose in a proposal to X/Open for a "Uniform Network Interface". π
Craig Metz, Jack McCann, Erik Nordmark, Tim Hartrick, and Mukesh Kacker made many contributions to this document. Ramesh Govindan made a number of contributions and co-authored an earlier version of this memo. π§‘
References π
- [1] Deering, S. and R. Hinden, "Internet Protocol, Version 6 (IPv6) Specification", RFC 2460, December 1998.
- [2] Hinden, R. and S. Deering, "IP Version 6 Addressing Architecture", RFC 2373, July 1998.
- [3] IEEE, "Protocol Independent Interfaces", IEEE Std 1003.1g, DRAFT 6.6, March 1997.
- [4] Stevens, W. and M. Thomas, "Advanced Sockets API for IPv6", RFC 2292, February 1998.
Authors' Addresses π§
Robert E. Gilligan
FreeGate Corporation
1208 E. Arques Ave.
Sunnyvale, CA 94086
Phone: +1 408 617 1004
EMail: gilligan@freegate.com
Susan Thomson
Bell Communications Research
MRE 2P-343, 445 South Street
Morristown, NJ 07960
Phone: +1 201 829 4514
EMail: set@thumper.bellcore.com
Jim Bound
Compaq Computer Corporation
110 Spitbrook Road ZK3-3/U14
Nashua, NH 03062-2698
Phone: +1 603 884 0400
EMail: bound@zk3.dec.com
W. Richard Stevens
1202 E. Paseo del Zorro
Tucson, AZ 85718-2826
Phone: +1 520 297 9416
EMail: rstevens@kohala.com
Full Copyright Statement β
Copyright (C) The Internet Society (1999). All Rights Reserved.
This document and translations of it may be copied and furnished to others, and derivative works that comment on or otherwise explain it or assist in its implementation may be prepared, copied, published and distributed, in whole or in part, without restriction of any kind, provided that the above copyright notice and this paragraph are included on all such copies and derivative works. However, this document itself may not be modified in any way, such as by removing the copyright notice or references to the Internet Society or other Internet organizations, except as needed for the purpose of developing Internet standards in which case the procedures for copyrights defined in the Internet Standards process must be followed, or as required to translate it into languages other than English. πΈ
The limited permissions granted above are perpetual and will not be revoked by the Internet Society or its successors or assigns. π
This document and the information contained herein is provided on an "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. π¦
π¦ where this page comes from
- ietf: rfc2553 1999-03
- π girlified by claude-haiku-5-5 on : a language model's rewrite of the original, under its terms