声明:本博客参考自《UNIX网络编程卷1》
套接口地址结构
IPv4套接口地址结构
Ubuntu:/usr/include/netinet/in.h
#include<netinet/in.h>
struct in_addr{
in_addr_t s_addr;
};
struct sockaddr_in {
uint8_t sin_len;
sa_family_t sin_family;
in_port_t sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
对上述的地址结构进行说明:
①sin_len-结构体长度字段。
②sin_family-协议族字段。可取的值为:AF_UNIX(本地通信)、AF_INET(IPv4)、AF_INT6(IPv6)
③sin_port-16位的端口号
④sin_addr-32位IP地址
⑤sin_zero-未使用备用
常见的套结构地址字段类型如下图所示。
备注:对32位IP地址的引用有两种形式,其一:serv.sin_addr。其二:serv.sin_addr.s_addr。
套接口为了使得API可以实现协议无关性,定义了一个通用的套接口
Ubuntu:/usr/include/x86_64-linux-gnu/bits/socket.h
#include <bits/socket.h>
struct sockaddr{
unit8_t sa_len;
sa_family_t sa_family;
char sa_data[14]
};
在使用套接口API时,通过将其它地址结构强转成此结构,传递给API。
IPv6套接口地址结构
Ubuntu:/usr/include/netinet/in.h
#include<netinet/in.h>
struct in6_addr{
uint8_t s6_addr[16];
};
#define SIN6_LEN
struct sockaddr_in6 {
uint8_t sin6_len;
sa_family_t sin6_family;
in_port_t sin6_port;
uint32_t sin6_flowinfo;
struct in6_addr sin6_addr;
uint32_t sin6_scope_id;
};
字段说明:
①sin6_family-地址族字段,在这里取AF_INET6
②sin6_flowinfo-流标字段。低20位为流标,高12位保留。
③sin6_scope_id-对于具备范围的地址,该字段标识其范围,常见的是链路局部地址的接口索引。
新的通用套接字地址结构
对与上述通用结构的几点说明。
①sockaddr_storage-足够大,可以容纳任何套接字地址结构。
②sockaddr_storage需要强转成其它类型,才可方位数据。
Unix域套接口地址与数据链路套接口地址
- Unix域套接口
Ubuntu:/usr/include/x86_64-linux-gnu/sys/un.h
/usr/include/Linux/un.h
#include<sys/un.h>
struct sockaddr_un{
sa_family_t sun_family;
char sun_path;
};
对与地址结构的说明
①sun_family-地址族这里的取值为:AF_LOCAL
②sun_path-路径名,为空字符结尾
- 数据链路套接口
Ubuntu中无此结构
#include<net/if_dl.h>
struct sockaddr_dl{
uint8_t sdl_len;
sa_family_t sdl_family;//AF_LINK
uint16_t sdl_index;//系统分配的索引
uint8_t sdl_type;
uint8_t sdl_nlen;
uint8_t sdl_alen;
uint8_t sdl_slen;
uint8_t sdl_date[12];
};
此结构一般很少用到,这里就不赘述
各个套结构地址结构的比较