Unix 几种网络地址
1.IPV4 internet addressstruct in_addr {
in_addr_t s_addr; /* 32-bit IPv4 address */
/* network byte ordered */
};
2.IPV4 socket addressstruct sockaddr_in {
uint8_t sin_len; /* length of structure (16) */
sa_family_t sin_family; /* AF_INET */
in_port_t sin_port; /* 16-bit TCP or UDP port number */
/* network byte ordered */
struct in_addr sin_addr; /* 32-bit IPv4 address */
/* network byte ordered */
char sin_zero[8]; /* unused */
};
3.IPV6 internet addressstruct in6_addr {
uint8_t s6_addr[16]; /* 128-bit IPv6 address */
/* network byte ordered */
};
4.IPV6 socket addressstruct sockaddr_in6 {
uint8_t sin6_len; /* length of this struct (28) */
sa_family_t sin6_family; /* AF_INET6 */
in_port_t sin6_port; /* transport layer port# */
/* network byte ordered */
uint32_t sin6_flowinfo; /* flow information, undefined */
struct in6_addr sin6_addr; /* IPv6 address */
/* network byte ordered */
uint32_t sin6_scope_id; /* set of interfaces for a scope */
};
5.Generic socket address struct sockaddr {
uint8_t sa_len;
sa_family_t sa_family; /* address family: AF_xxx value */
char sa_data[14]; /* protocol-specific address */
};
6.New Generic socket address struct sockaddr_storage {
uint8_t ss_len; /* length of this struct (implementation dependent) */
sa_family_t ss_family; /* address family: AF_xxx value */
/* implementation-dependent elements to provide:
* a) alignment sufficient to fulfill the alignment requirements of
* all socket address types that the system supports.
* b) enough storage to hold any type of socket address that the
* system supports.
*/
};
注意到,
所有的socket address的开头两个字段是uint8_t ss_len和sa_family_t ss_family,第一个字段指明数据结构的长度,可以用来定位地址结构,第二个指定地址类型,可以用来区别各种地址。正因为前两个字段一样,才能用sockaddr或者sockaddr_storage统一表示socket address,应用程序只需要将具体的地址类型(如sockaddr_in6或者sockaddr_in)显示的转换成通用地址类型(sockaddr或者sockaddr_storage),内核网络模块就可定位地址数据结构并判断地址类型。现在的实现中,如connect,bind等,都采用sockaddr作为通用地址。
下面的图清晰的说明了各种网络地址的关系