Windows API Reference

Address Families

This topic discusses address families used in Windows Sockets 2. Address families define the protocol family that a socket will use. Common address families include Internet Protocol version 4 (IPv4) and Internet Protocol version 6 (IPv6).

Overview

When creating a socket using the socket function, you must specify the address family. This informs the operating system which networking protocol suite the socket should use for communication. The most common address families are:

Common Address Families and Their Constants

The following table lists some of the most frequently used address family constants defined in the Winsock header files (like winsock2.h):

Constant Description Protocol Family
AF_INET Address family for Internet Protocol (IP) version 4. IPv4
AF_INET6 Address family for Internet Protocol (IP) version 6. IPv6
AF_UNSPEC Unspecified address family. The provider will select the most appropriate address family. Any
AF_IPX Address family for Novell NetWare IPX/SPX. (Deprecated) IPX/SPX
AF_NETBIOS Address family for NetBIOS. (Deprecated) NetBIOS

Using Address Families

You specify the address family as the first parameter to the socket function:


#include <winsock2.h>

// Example for creating an IPv4 TCP socket
SOCKET sock_ipv4_tcp = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

// Example for creating an IPv6 UDP socket
SOCKET sock_ipv6_udp = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);

// Example for letting the system choose the address family
SOCKET sock_unspecified = socket(AF_UNSPEC, SOCK_STREAM, 0);
            
Note: When using AF_UNSPEC, the subsequent parameters (like SOCK_STREAM or SOCK_DGRAM) might influence the chosen address family. For instance, if you specify SOCK_STREAM, the system might default to IPv4 TCP.

Socket Types and Protocols

The address family is often used in conjunction with socket types (e.g., SOCK_STREAM for reliable, connection-oriented communication, and SOCK_DGRAM for unreliable, connectionless communication) and protocols (e.g., IPPROTO_TCP, IPPROTO_UDP) to fully define the socket's behavior.

IPv4 vs. IPv6 Considerations

When developing network applications, it's increasingly important to support both IPv4 and IPv6. Using AF_INET6 allows your application to communicate with both IPv6 and, in many cases, IPv4 addresses (through dual-stack mechanisms).

Tip: For modern applications, it is recommended to design for IPv6 support by using AF_INET6 and handling the differences in address structures (like SOCKADDR_IN6 vs. SOCKADDR_IN) within your code. Using AF_UNSPEC can be a convenient way to let the underlying system determine the best address family if explicit control isn't required.

Related Topics