8.2 IP地址和域名之间的转换
2025/11/14大约 2 分钟
8.2 IP地址和域名之间的转换
利用域名获取ip地址
man gethostbyname struct hostent *gethostbyname(const char *name);
The hostent structure is defined in <netdb.h> as follows:
struct hostent {
char *h_name; /* official name of host */
char **h_aliases; /* alias list */
int h_addrtype; /* host address type */
int h_length; /* length of address */
char **h_addr_list; /* list of addresses */
}实现:
const char *hostname = "baidu.com";
struct hostent *host = gethostbyname(hostname);
if(!host)
{
fprintf(stderr, "gethost error: %s\n", hstrerror(h_errno));
exit(1);
}
printf("name:%s\n", host->h_name);
for(int i=0; host->h_aliases[i]; i++)
printf("Aliases %d: %s \n", host->h_aliases[i]);
printf("Address type:%s\n",
(host->h_addrtype == AF_INET) ? "AF_INET" : "AF_INET6");
for(int i=0; host->h_addr_list[i]; i++)
printf("IP addr %d: %s \n", i+1,
inet_ntoa(*(struct in_addr*)host->h_addr_list[i]));| 行号 | 功能 | 说明 |
|---|---|---|
| 3-7 | 错误处理 | 错误码存储再h_errno中,通过hstrerror( )获取错误信息 |
| 9、13 | 数组尾后元素是NULL | |
| 15 | 获取字符串类型的ip地址 | h_addr_list实际上指向的是in_addr变量,而非字符串ip地址。至于为什么函数参数中定义为char 类型,而非in_addr类型 是为了兼容其他地址类型,但是由于当时没有通用类型void,就使用char * 作为通用类型。 |
效果:
name:baidu.com
Address type:AF_INET
IP addr 1: 182.61.202.236
IP addr 2: 182.61.202.46
IP addr 3: 182.61.244.44
IP addr 4: 182.61.244.149和使用nslookup 查询的结果一致
利用ip地址获取域名
#include <sys/socket.h> /* for AF_INET */
struct hostent *gethostbyaddr(const void *addr,
socklen_t len, int type);实现:
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_addr.s_addr = inet_addr(argv[1]);
struct hostent *host = gethostbyaddr((void*)&addr.sin_addr, sizeof(addr.sin_addr), AF_INET);
if(!host)
{
fprintf(stderr, "gethost error: %s", hstrerror(h_errno));
exit(1);
}
//打印host 信息 和 前面一致| 行号 | 功能 | 说明 |
|---|---|---|
| 1-3 | 从参数中获取要查询的ip地址 | |
| 4 | 获取ip地址对应的域名以及域名对应的ip地址信息 | addr参数是结构体内存储的32位整数值,而非字符串 |
效果:
$ ./Network 182.61.244.44
gethost error: Unknown host
nslookup guzhoutingxue.github.io
服务器: UnKnown
Address: fe80::1
非权威应答:
名称: guzhoutingxue.github.io
Addresses: 2606:50c0:8002::153
2606:50c0:8003::153
2606:50c0:8000::153
2606:50c0:8001::153
185.199.109.153
185.199.110.153
185.199.111.153
185.199.108.153
./Network 185.199.108.153
name:cdn-185-199-108-153.github.com
Address type:AF_INET
IP addr 1: 185.199.108.153| 行号 | 功能 | 说明 |
|---|---|---|
| 1-2 | 查询百度服务器ip地址对应的host信息 返回的host为NULL | |
| 4-17 | 通过nslookup查询我的博客的ip地址 | |
| 19-22 | 查看博客服务器ip对应的host信息 | 可以查询到host信息,就是name 不一样 |
问:为什么gethostbyaddr查询到的host ip地址只有1个?是设计成这样还是?
问:official name of host 是怎么确定的?是服务器的用户名?
问:为什么不能查询百度服务器ip 对应的host?
通过nslookup 查询
PS C:\Users\mingstudent\Desktop> nslookup 182.61.244.44
服务器: UnKnown
Address: fe80::1
*** UnKnown 找不到 182.61.244.44: Non-existent domain百度不支持Reverse DNS Lookup