gpt4 book ai didi

c - gethostbyname() 或 getnameinfo() 如何在后台工作?

转载 作者:太空宇宙 更新时间:2023-11-04 08:49:11 28 4
gpt4 key购买 nike

gethostbyname()getnameinfo() 如何在后台工作?

#include <stdlib.h>
#include <stdio.h>
#include <netdb.h>

/* paddr: print the IP address in a standard decimal dotted format */
void
paddr(unsigned char *a)
{
printf("%d.%d.%d.%d\n", a[0], a[1], a[2], a[3]);
}

main(int argc, char **argv) {
struct hostent *hp;
char *host = "google.com";
int i;

hp = gethostbyname(host);
if (!hp) {
fprintf(stderr, "could not obtain address of %s\n", host);
return 0;
}
for (i=0; hp->h_addr_list[i] != 0; i++)
paddr((unsigned char*) hp->h_addr_list[i]);
exit(0);
}

google.com 的输出:

74.125.236.198
74.125.236.199
74.125.236.206
74.125.236.201
74.125.236.200
74.125.236.196
74.125.236.193
74.125.236.197
74.125.236.194
74.125.236.195
74.125.236.192

www.google.com 的输出:

74.125.236.210
74.125.236.209
74.125.236.212
74.125.236.208
74.125.236.211
  1. 上述程序是否会在 internet 中进行检查以解析为 IP?
  2. 为什么它显示较少的 www.google.com IP 地址而更多显示 google.com

最佳答案

在 Linux 系统上,glibc 中实现的 gethostbyname() 调用根据配置文件 /etc/host.conf/etc/nsswitch.conf 执行查找.

通常在默认配置中,它会首先在 /etc/hosts 文件中查找是否存在给定名称的本地条目,如果存在,则返回该条目。否则它将继续使用 DNS 协议(protocol),该协议(protocol)又由 /etc/resolv.conf 配置,其中声明了名称服务器。

可以配置更复杂的设置来查找 LDAP 服务器、数据库等。

您还可以查看一些手册页,例如 man 5 nsswitch.conf

关于c - gethostbyname() 或 getnameinfo() 如何在后台工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20284094/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com