struct hostent * gethostbyaddr(const char *addr, socklen_t len, int family);
gethostbyaddr.c
采用这种方法获取信息,需要将不成功的 ip
与对应域名
添加到hosts
文件,否则会失败(如下百度ip失败,本地成功)
将百度ip与域名对应关系添加到/etc/hosts
中,就可以成功了。
没找到源码,不知道是怎么实现的,为什么已经有了ip,程序还会去hosts文件内查询呢?
不过似乎不成功的原因是目标ip不支持这种查询方式 ?(存疑),我换了64.233.189.104
(google)就可以了(hosts未修改)。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netdb.h>
void error_handling(const char *message);
int main(int argc, char const *argv[]) {
int i;
struct hostent *host;
struct sockaddr_in addr;
if(argc != 2) {
printf("Usage : %s <addr>\n",argv[0]);
exit(1);
}
// struct hostent * gethostbyaddr(const char *addr, socklen_t len, int family);
// addr: 含有IP地址信息的in_addr结构体指针
memset(&addr, 0, sizeof(addr));
addr.sin_addr.s_addr = inet_addr(argv[1]);
host = gethostbyaddr((const char*)&addr.sin_addr, 4, AF_INET);
if(!host)
error_handling("gethost.. error");
printf("Official name %s \n",host -> h_name);
for(i = 0; host -> h_aliases[i]; i++)
printf("Aliases %d: %s \n", i+1, host -> h_aliases[i]);
printf("Address type: %s \n",(host -> h_addrtype == AF_INET) ? "AF_INET" : "AF_INET6");
for(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])) );
return 0;
}
void error_handling(const char *message) {
fputs(message,stderr);
fputs("\n",stderr);
exit(1);
}
-
hosts
文件是Linux
系统上一个负责ip地址与域名快速解析的文件,以ascii格式保存在/etc/目录下。hosts文件包含了ip地址与主机名之间的映射,还包括主机的别名。在没有域名解析服务器的情况下,系统上的所有网络程序都通过查询该文件来解析对应于某个主机名的ip地址,否则就需要使用dns服务程序来解决。通过可以将常用的域名和ip地址映射加入到hosts文件中,实现快速方便的访问。 -
优先级 :
dns缓存 > hosts > dns服务
-
hosts
文件作用- 一个主要的作用是:线下环境模拟,通信双方在同一个局域网内想通过internet上的域名相互访问,则只需要修改自己的
/etc/hosts
文件内容即可。
- 一个主要的作用是:线下环境模拟,通信双方在同一个局域网内想通过internet上的域名相互访问,则只需要修改自己的
用gethostbyname()
倒是没什么问题:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netdb.h>
void error_handling(const char *message);
int main(int argc, char const *argv[]) {
int i;
struct hostent *host;
if(argc != 2) {
printf("Usage : %s <addr>\n",argv[0]);
exit(1);
}
// struct hostent * gethostbyname(const char *hostname);
host = gethostbyname(argv[1]);
if(!host)
error_handling("gethost.. error");
printf("Official name %s \n",host -> h_name);
for(i = 0; host -> h_aliases[i]; i++)
printf("Aliases %d: %s \n", i+1, host -> h_aliases[i]);
printf("Address type: %s \n",(host -> h_addrtype == AF_INET) ? "AF_INET" : "AF_INET6");
for(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])) );
return 0;
}
void error_handling(const char *message) {
fputs(message,stderr);
fputs("\n",stderr);
exit(1);
}