c - gethostbyname 有什么问题?

标签 c linux gethostbyname

我正在使用我在 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/

相关文章:

linux - 用户地址内存是如何组织的?

c - 我们如何缓存 gethostbyname 的结果?

c - 使用不可缓存内存的最佳实践

c - 带有 void* 的算术指针

linux - AWK如何计算累计和并在超过预定义整数后停止?

c++ - gethostbyname 中的 malloc_consolidate 出现段错误

linux - gethostbyname_r() 调用始终返回的不可解析主机,并将 h_errnop 设置为 TRY_AGAIN(在 Ubuntu 19.04 和 20.04 上)

c - 传递长度为 "constant"的二维数组

c - 使用指针在 C 中查找 char 的索引

linux控制台如何将代码页更改为dos cp437