阅读背景:

为什么我在getaddrinfo()返回的链表中得到重复的addrinfo对象?

来源:互联网 

Here is my code.

这是我的代码。

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

int main()
{
    struct addrinfo hints, *res, *p;
    int error;

    memset(&hints, 0, sizeof hints);

    /* If we comment or remove the following line, the duplicate entries
     * disappear */
    hints.ai_family = AF_INET;

    error = getaddrinfo("localhost", "http", &hints, &res);
    if (error != 0) {
        printf("Error %d: %s\n", error, gai_strerror(error));
        return 1;
    }

    for (p = res; p != NULL; p = p->ai_next)
    {
        if (p->ai_family == AF_INET) {
            struct sockaddr_in *addr = (struct sockaddr_in *) p->ai_addr;
            char ip[INET_ADDRSTRLEN];

            printf("ai_flags: %d; ai_family: %d; ai_socktype: %d; "
                   "ai_protocol: %2d; sin_family: %d; sin_port: %d; "
                   "sin_addr: %s; ai_canonname: %s\n",
                   p->ai_flags, p->ai_family, p->ai_socktype,
                   p->ai_protocol, addr->sin_family, ntohs(addr->sin_port),
                   inet_ntop(AF_INET, &addr->sin_addr, ip, INET_ADDRSTRLEN),
                   p->ai_canonname);
        } else if (p->ai_family == AF_INET6) {
            struct sockaddr_in6 *addr = (struct sockaddr_in6 *) p->ai_addr;
            char ip[INET6_ADDRSTRLEN];

            printf("ai_flags: %d; ai_family: %d; ai_socktype: %d; "
                   "ai_protocol: %2d; sin6_family: %d; sin6_port: %d; "
                   "sin6_addr: %s; ai_canonname: %s\n",
                   p->ai_flags, p->ai_family, p->ai_socktype,
                   p->ai_protocol, addr->sin6_family, ntohs(addr->sin6_port),
                   inet_ntop(AF_INET6, &addr->sin6_addr, ip, INET6_ADDRSTRLEN),
                   p->ai_canonname);
        }
    }

    return 0;
}
#include <stdio.h>



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: