gethostbyname 与 getaddrinfo
IPV4 与 IPV6 区别
| IPV4 | IPV6 | |
|---|---|---|
| 协议族 | PF_INET | PF_INET6 |
| 地址族 | AF_INET | AF_INET6 |
| 数据结构 | in_addr_sockaddr_in | in6_addr_sockaddr_in6 |
| 网络地址转换函数 | inet_aton/inet_addr | inet_pton |
| 网络地址转换函数 | inet_ntoa | inet_ntop |
| 地址转换函数 | gethostbyname | getaddrinfo |
| 地址转换函数 | gethostbyaddr | getnameinfo |
网络地址转换函数
网络地址函数用于在 ASCII 字符串(点分十进制数串 “192.168.110.1”) 与网络字节序的二进制(存放在 socket 地址结构中)之间转换网络地址。
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int inet_aton(const char *cp, struct in_addr *inp);
in_addr_t inet_addr(const char *cp); // 已废弃
char *inet_ntoa(struct in_addr in);
上述函数只能处理 IPV4,下面的函数 IPV4 IPV6 通用
#include <arpa/inet.h>
//inet_ntop - convert IPv4 and IPv6 addresses from binary to text form
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
//inet_pton - convert IPv4 and IPv6 addresses from text to binary form
int inet_pton(int af, const char *src, void *dst);
查找主机名
gethostbyname 和 gethostbyaddr 仅支持 IPV4,替换接口为 getaddrinfo 和 getnameinfo
name -> IP : gethostbyname getaddrinfo
IP -> name : gethostbyaddr getnameinfo