Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 什么';gethostbyname有什么问题吗?_C_Linux_Gethostbyname - Fatal编程技术网

C 什么';gethostbyname有什么问题吗?

C 什么';gethostbyname有什么问题吗?,c,linux,gethostbyname,C,Linux,Gethostbyname,我正在使用在中找到的这段代码片段执行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 ma

我正在使用在中找到的这段代码片段执行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;
}
工作正常,但如果我试图解决一个不完整的IP地址,我会得到这个

./test 10.1.1
Hostname: 10.1.1
IP Address: 10.1.0.1
我预计会出现如下错误

./test www.google
gethostbyname(): : Unknown host
但这个计划似乎奏效了

知道为什么吗?

说:

gethostbyname()的name参数应为节点名;未指定传递数字地址字符串时gethostbyname()的行为。对于IPv4,数字地址字符串应采用inet_addr()中描述的点十进制表示法

因此,从POSIX的角度来看,在向其传递IP地址时,您不能期望有任何结果

在我的系统上,显示如下:

如果名称是IPv4或IPv6地址,则不执行任何查找,gethostbyname()只需将名称复制到h_name字段中,并将其在h_addr中的等效结构复制到返回的hostent结构的h_addr_列表[0]字段中

它没有说明如果您向它传递一个不完整的IP地址会发生什么,因此任何事情都可能发生,包括您观察到的行为


有关如何在系统上实现gethostbyname的详细信息,您可以查看函数和/或源代码(如果可用)的文档。

这不是一个bug,而是inet_aton()函数的一个功能:

描述

函数的作用是:在 Internet标准点符号,指向网络地址,并存储 提供的结构中的地址

使用点符号指定的值采用以下形式之一:

a.b.c.d当指定四个部分时,每个部分都被解释为一个字节的数据,并从左到右分配给互联网地址的四个字节

a.b.c 当指定一个由三部分组成的地址时,最后一部分将被解释为16位量,并放在网络地址最右边的两个字节中。这使得三部分地址格式便于将B类网络地址指定为128.net.host


例如,您可以阅读更多信息。

我刚刚尝试了getaddrinfo的代码,但是10.1.1 sill在10.1.0.1中解析。。。是虫子吗?我遗漏了什么吗?除了从
inet\u addr
“a.b.c.中指定三部分地址时,最后一部分应解释为16位数量,并放在网络地址的最右边两个字节中。这使得三部分地址格式便于将b类网络地址指定为“128.net.host”“因此,Linux说明了如何处理虚线IP地址,
inet\u addr
定义了
10.1.1
是一个虚线地址,意思与
10.1.0.1
相同,因此,提问者观察到的行为是在Linux上定义和预期的。是否有任何东西表明
gethostbyname
应该调用
inet\u aton
?@cHao:当gethostbyname()被指定一个点式ip作为参数(如OP的场景中)时,它使用inet\u aton()如果名称是IPv4或IPv6地址,则不执行任何查找,gethostbyname()只需将名称复制到h_name字段中,并将其在h_addr中的等效结构复制到返回的hostent结构的h_addr_列表[0]字段中
./test www.google
gethostbyname(): : Unknown host