ip地址转换

通常,我们用点分十进制字符串表示ipv4地址(192.168.1.1),用十六进制字符串表示ipv6地址(fe80::20c:29ff:fee9:4bcc)。

ipv4转换函数

#include <arpa/inet.h>
// 字符串ip地址转换成网络字节序ip地址,地址存储在ip指向的结构中,成功返回1,否则0 int inet_aton(const char *cp, struct in_addr *ip); // 功能同上,失败返回INADDR_NONE,不推荐使用 in_addr_t inet_addr(const char *cp); // 网络字节序整数ip地址转换成字符串ip地址,函数内部使用静态变量存储转换结果(该函数不可重入) char *inet_ntoa(struct in_addr in);

ipv4&ipv6转换函数

#include <arpa/inet.h>

// 字符串ip地址转换成网络字节序整数ip地址
int inet_pton(int af, const char *src, void *dst);

// 网络字节序整数ip地址转换成字符串ip地址,成功返回目标存储单元地址,失败返回NULL并设置errno
const char *inet_ntop(int af, const void *src, char *dst, socklen_t len);

af 为 AF_INET 或 AF_INET6
len 为 目标存储单元大小,如下宏定义可以解决
#inclued <netinet/in.h>
#define INET_ADDRSTRLEN 16       // for IPv4
#define INET6_ADDRSTRLEN 46      // for IPv6
在孤独中思考,在思考中成熟,在成熟中升华
原文地址:https://www.cnblogs.com/laogaoyang/p/5881889.html