inet_ntop()
是一个用于将二进制整数形式的网络地址(如 IPv4/IPv6)转换为人类可读的字符串格式(如 "192.168.1.1"
)的函数,属于套接字编程中的常用工具。以下是详细说明和示例:
函数原型
#include <arpa/inet.h>
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
参数说明
参数 | 类型 | 描述 |
---|---|---|
af |
int |
地址族:AF_INET (IPv4)或 AF_INET6 (IPv6)。 |
src |
const void* |
指向二进制网络地址的指针(如 struct in_addr 或 struct in6_addr )。 |
dst |
char* |
存储转换后字符串的缓冲区。 |
size |
socklen_t |
缓冲区 dst 的大小(通常用宏如 INET_ADDRSTRLEN , INET6_ADDRSTRLEN )。 |
返回值
- 成功:返回指向字符串地址的指针(即
dst
)。 - 失败:返回
NULL
,并设置errno
。
使用示例
1. IPv4地址转换
#include <stdio.h>
#include <arpa/inet.h>
int main() {
struct in_addr addr;
addr.s_addr = htonl(0xC0A80101); // 二进制形式:192.168.1.1
char ip_str[INET_ADDRSTRLEN]; // IPv4缓冲区大小至少16字节
if (inet_ntop(AF_INET, &addr, ip_str, sizeof(ip_str))) {
printf("IPv4 Address: %s\n", ip_str); // 输出:192.168.1.1
} else {
perror("inet_ntop failed");
}
return 0;
}
2. IPv6地址转换
#include <stdio.h>
#include <arpa/inet.h>
int main() {
struct in6_addr addr6 = IN6ADDR_ANY_INIT; // ::0 (全零地址)
char ip6_str[INET6_ADDRSTRLEN]; // IPv6缓冲区大小至少46字节
if (inet_ntop(AF_INET6, &addr6, ip6_str, sizeof(ip6_str))) {
printf("IPv6 Address: %s\n", ip6_str); // 输出:::
} else {
perror("inet_ntop failed");
}
return 0;
}
关键注意事项
线程安全
inet_ntop()
是线程安全的,但需确保目标缓冲区 (dst
) 不被其他线程修改。
缓冲区大小
- IPv4:使用宏
INET_ADDRSTRLEN
(16字节)。
- IPv6:使用宏
INET6_ADDRSTRLEN
(46字节)。
- IPv4:使用宏
错误处理
- 检查返回值是否为
NULL
,并通过errno
定位问题:if (!inet_ntop(...)) { perror("Error"); }
- 检查返回值是否为
替代函数对比
不推荐:旧版函数如inet_ntoa()
是非线程安全的。
如果需要进一步探讨网络编程的其他接口或场景,可以随时提问!
内容由零声教学AI助手提供,问题来源于学员提问