我正在使用我在 http://www.kutukupret.com/2009/09/28/gethostbyname-vs-getaddrinfo/ 中找到的这段代码执行 DNS 查找
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[ ]) {
struct hostent *h;
/* error check the command line */
if(argc != 2) {
fprintf(stderr, "Usage: %s hostname\n", argv[0]);
exit(1);
}
/* get the host info */
if((h=gethostbyname(argv[1])) == NULL) {
herror("gethostbyname(): ");
exit(1);
}
else
printf("Hostname: %s\n", h->h_name);
printf("IP Address: %s\n", inet_ntoa(*((struct in_addr *)h->h_addr)));
return 0;
}
我面对一个奇怪的事实
./test www.google.com
Hostname: www.l.google.com
IP Address: 209.85.148.103
工作正常,但如果我尝试解析不完整的 IP 地址,我会得到这个
./test 10.1.1
Hostname: 10.1.1
IP Address: 10.1.0.1
我希望出现如下错误
./test www.google
gethostbyname(): : Unknown host
但该程序似乎有效。
知道为什么吗?
最佳答案
这不是错误,而是 inet_aton() 函数的一个特性:
DESCRIPTION
The inet_aton() function converts the specified string, in the Internet standard dot notation, to a network address, and stores the address in the structure provided.
Values specified using dot notation take one of the following forms:
a.b.c.d When four parts are specified, each is interpreted as a byte of data and assigned, from left to right, to the four bytes of an internet address.
a.b.c When a three-part address is specified, the last part is interpreted as a 16-bit quantity and placed in the rightmost two bytes of the network address. This makes the three-part address format convenient for specifying Class B network addresses as 128.net.host.
您可以阅读更多相关信息 there ,例如。
关于c - gethostbyname 有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6677077/