#include <arpa/inet.h>

#include <arpa/inet.h>
寻觅~流光#include <arpa/inet.h>
<arpa/inet.h>
是 网络编程 核心头文件,提供 IP 地址转换 和 字节序处理 功能,主要用于 IPv4/IPv6 套接字编程(Socket Programming)。
1. 核心功能
功能 | 关键函数/宏 | 用途 |
---|---|---|
IP 地址转换 | inet_aton() , inet_addr() , inet_ntoa() | IPv4 字符串 ↔ 二进制转换 |
现代 IP 转换 | inet_pton() , inet_ntop() | 支持 IPv4/IPv6 的可移植转换 |
字节序转换 | htons() , htonl() , ntohs() , ntohl() | 主机字节序 ↔ 网络字节序(大端序) |
2. 详细函数解析
2.1 IP 地址转换(IPv4)
(1) inet_aton()
- 字符串 → 二进制(推荐)
1 | int inet_aton(const char *cp, struct in_addr *inp); |
功能:将点分十进制 IPv4 地址(如
"192.168.1.1"
)转换为struct in_addr
。返回值:
- 成功:
1
。 - 无效地址:
0
。
- 成功:
示例:
1
2
3
4
5
6
struct in_addr addr;
if (inet_aton("192.168.1.1", &addr)) {
printf("Binary: 0x%x\n", addr.s_addr);
}
(2) inet_addr()
- 字符串 → 二进制(已废弃)
1 | in_addr_t inet_addr(const char *cp); |
- 问题:无法区分
"255.255.255.255"
(合法)和错误返回(INADDR_NONE
)。 - 替代方案:使用
inet_aton()
或inet_pton()
。
(3) inet_ntoa()
- 二进制 → 字符串
1 | char *inet_ntoa(struct in_addr in); |
注意:返回静态缓冲区,非线程安全!
示例:
1
2
3struct in_addr addr;
addr.s_addr = 0xC0A80101; // 192.168.1.1
printf("IP: %s\n", inet_ntoa(addr));
2.2 现代 IP 转换(IPv4/IPv6)
(1) inet_pton()
- 字符串 → 二进制(可移植)
1 | int inet_pton(int af, const char *src, void *dst); |
参数:
af
:地址族(AF_INET
或AF_INET6
)。src
:输入字符串(如"192.168.1.1"
或"::1"
)。dst
:输出缓冲区(struct in_addr
或struct in6_addr
)。
返回值:
- 成功:
1
。 - 无效格式:
0
。 - 错误:
-1
(errno
设置)。
- 成功:
示例:
1
2
3
4
5struct in_addr ipv4;
inet_pton(AF_INET, "192.168.1.1", &ipv4);
struct in6_addr ipv6;
inet_pton(AF_INET6, "::1", &ipv6);
(2) inet_ntop()
- 二进制 → 字符串(可移植)
1 | const char *inet_ntop(int af, const void *src, char *dst, socklen_t size); |
参数:
size
:目标缓冲区大小(INET_ADDRSTRLEN
或INET6_ADDRSTRLEN
)。
返回值:
- 成功:
dst
。 - 失败:
NULL
(errno
设置)。
- 成功:
示例:
1
2
3char str[INET6_ADDRSTRLEN];
struct in6_addr ipv6 = IN6ADDR_LOOPBACK_INIT;
inet_ntop(AF_INET6, &ipv6, str, sizeof(str)); // "::1"
2.3 字节序转换
函数 | 含义 | 示例 |
---|---|---|
htons() | Host to Network (16-bit) | htons(80) → 大端序的 80(HTTP 端口) |
htonl() | Host to Network (32-bit) | htonl(0xC0A80101) → 网络序 IP |
ntohs() | Network to Host (16-bit) | ntohs(received_port) |
ntohl() | Network to Host (32-bit) | ntohl(received_ip) |
示例:
1 | uint16_t port = 80; |
3. 关键结构体
IPv4 地址结构
1 | struct in_addr { |
通用地址结构(用于 connect()
/bind()
)
1 | struct sockaddr_in { |
4. 完整示例
将 IP 和端口转换为网络格式
1 |
|
5. 注意事项
- 线程安全:
inet_ntoa()
使用静态缓冲区,非线程安全!优先用inet_ntop()
。
- IPv6 支持:
inet_pton()
/inet_ntop()
是 IPv6 兼容的推荐方式。
- 错误处理:
- 检查
inet_pton()
的返回值,无效输入可能导致崩溃。
- 检查
- 字节序问题:
- 所有网络传输的数据(如端口、IP)必须用
htons()
/htonl()
转换。
- 所有网络传输的数据(如端口、IP)必须用
6. 总结
<arpa/inet.h>
的核心用途:
- IP 字符串 ↔ 二进制:
- IPv4:
inet_aton()
,inet_ntoa()
(旧) →inet_pton()
,inet_ntop()
(新)。 - IPv6:仅支持
inet_pton()
,inet_ntop()
。
- IPv4:
- 字节序转换:
htons()
,htonl()
,ntohs()
,ntohl()
。
适用于 Socket 编程、服务器开发、网络工具(如 ping
、traceroute
)。
评论
匿名评论隐私政策
TwikooWaline
✅ 你无需删除空行,直接评论以获取最佳展示效果