inet_ntop() 函数的作用是将IPv4/IPv6 地址从二进制形式转换到 text 形式,它是 inet_pton() 的逆向函数,定义如下:
[Plain Text] 纯文本查看 复制代码 #include <arpa/inet.h>
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
第 1 个参数 af 要么是 AF_INET,要么是 AF_INET6,前者表示转换到 IPv4 地址,后者表示转换到 IPv6 地址。
第 2 个参数 src 是 IPv4 或 IPv6 地址的二进制形式(可由 inet_pton() 函数转换二来),它们存储在 struct in_addr 或 struct in6_addr 这两个结构中,这两个结构定义如下:
[C++] 纯文本查看 复制代码 /* Internet address. */
typedef uint32_t in_addr_t;
struct in_addr
{
in_addr_t s_addr;
};
/* IPv6 address */
struct in6_addr
{
union
{
uint8_t __u6_addr8[16];
#if defined __USE_MISC || defined __USE_GNU
uint16_t __u6_addr16[8];
uint32_t __u6_addr32[4];
#endif
} __in6_u;
#define s6_addr __in6_u.__u6_addr8
#if defined __USE_MISC || defined __USE_GNU
# define s6_addr16 __in6_u.__u6_addr16
# define s6_addr32 __in6_u.__u6_addr32
#endif
};
其中 s_addr 是个无符号整型值,__u6_addr8[16] 是一个含有 16 个 unsigned char 类型元素的数组。
第 3 个参数用来存放转换后结果的缓冲区。
第 4 个参数表示第 3 个参数缓冲区的大小。
测试代码见:http://www.groad.net/bbs/read.php?tid-7155.html |