0

大家
好,我试图从我的 res 结构中获取 IP 地址,但我仍然无法通过它,有人知道如何获取它们吗?

int main(int argc, char **argv) {
    struct addrinfo hints, *res;

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

    if(getaddrinfo(NULL, "50000", &hints, &res) != 0) {
        perror("Error in getaddrinfo\n");
        exit(-1);
    }

    //Print out the IPs from res

    return 0;
}
4

2 回答 2

2

IP 地址存储在ai_addr字段中。您可以使用inet_ntop获取 ip 地址,如下所示:

#include <stdio.h>
#include <arpa/inet.h>
#include <netdb.h>

void print_ips(struct addrinfo *lst) {
    /* IPv4 */
    char ipv4[INET_ADDRSTRLEN];
    struct sockaddr_in *addr4;
    
    /* IPv6 */
    char ipv6[INET6_ADDRSTRLEN];
    struct sockaddr_in6 *addr6;
    
    for (; lst != NULL; lst = lst->ai_next) {
        if (lst->ai_addr->sa_family == AF_INET) {
            addr4 = (struct sockaddr_in *) lst->ai_addr;
            inet_ntop(AF_INET, &addr4->sin_addr, ipv4, INET_ADDRSTRLEN);
            printf("IP: %s\n", ipv4);
        }
        else if (lst->ai_addr->sa_family == AF_INET6) {
            addr6 = (struct sockaddr_in6 *) lst->ai_addr;
            inet_ntop(AF_INET6, &addr6->sin6_addr, ipv6, INET6_ADDRSTRLEN);
            printf("IP: %s\n", ipv6);
        }
    }
}
于 2013-11-07T16:13:51.353 回答
0

使用getnameinfowithNI_NUMERICHOSTNI_NUMERICSERVflags 来获取表示主机和端口的数字形式的字符串。

于 2013-11-06T18:06:59.363 回答