使用主机名获取主机信息的例子

ccbbcc CSDN会员 ccbbcc 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

代码:

#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>

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

    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;

    if ((status = getaddrinfo("example.com", NULL, &hints, &res)) != 0) {
        fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
        return 1;
    }

    for (struct addrinfo *p = res; p != NULL; p = p->ai_next) {
        switch (p->ai_family) {
            case AF_INET:
                printf("Address family: AF_INET\n");
                break;
            case AF_INET6:
                printf("Address family: AF_INET6\n");
                break;
            default:
                printf("Address family: unknown\n");
                break;
        }
        printf("Socket type: %d\n", p->ai_socktype);
        printf("Protocol: %d\n", p->ai_protocol);
        char ipstr[INET6_ADDRSTRLEN];
        void *addr;
        if (p->ai_family == AF_INET) {
            struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
            addr = &(ipv4->sin_addr);
        } else {
            struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
            addr = &(ipv6->sin6_addr);
        }
        inet_ntop(p->ai_family, addr, ipstr, sizeof(ipstr));
        printf("Address: %s\n", ipstr);
    }

    freeaddrinfo(res);
    return 0;
}

运行结果

chenbingjy@ubuntu:/home/samba/5$ ./hostent
get the host: www.baidu.com addr
name:www.a.shifen.com
type:AF_INET
length:4
段错误 (核心已转储)

请问专家,那里错了?谢谢

...全文

相关推荐

评论
收藏 已收藏
分享
返回顶部
ccbbcc CSDN会员
Linux/Unix社区 18,828 成员 11,488 内容