1

这是一个简单的程序,我编写它是为了找出一个域的所有A record.

我遵守它并且没有收到任何错误或警告。

然后我运行它,我发现它给出了错误的IP,例如:

./a.out www.google.com

2.0.0.0

2.0.0.0

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>

int main(int argc, char *argv[])
{
    struct addrinfo addrC;
    struct addrinfo *addrL;
    struct addrinfo *temp;

    memset(&addrC, 0, sizeof(addrC));
    addrC.ai_family = AF_INET;
    addrC.ai_socktype = SOCK_STREAM;
    addrC.ai_protocol = IPPROTO_TCP;

    if (getaddrinfo(argv[1], "http", &addrC, &addrL) != 0)
    {
        perror("getaddrinfo!");
        exit(1);
    }

    for (temp = addrL; temp != NULL; temp = temp->ai_next)
    {
        char addrBuf[BUFSIZ];
        void *addrCount = &((struct sockaddr_in*)temp)->sin_addr;
        inet_ntop(temp->ai_addr->sa_family, addrCount, addrBuf, sizeof(addrBuf));
        printf("%s\n", addrBuf);
    }
    for (temp = addrL; temp != NULL; temp = addrL)
    {
        addrL = temp->ai_next;
        free(temp);
    }
    return 0;
}

为什么?以及如何纠正它?

4

2 回答 2

1

另一个答案是正确的,但我建议使用getnameinfo(使用 NI_NUMERICHOST) 而不是inet_ntop. 那么你一开始就不会有这个错误。

此外,您不应该循环并从getaddrinfo. 你调用freeaddrinfo释放整个数组。

于 2012-03-11T10:48:36.763 回答
1

您在循环内的指针转换有错误,它应该是:

void *addrCount = &((struct sockaddr_in*)temp->ai_addr)->sin_addr;

否则,您正在阅读垃圾并将垃圾传递给inet_ntop,因此您会得到垃圾 :)

于 2012-03-11T07:50:11.733 回答