如何从sockaddr获取IP地址

时间:2013-11-06 16:29:26

标签: c sockets ip

大家好嗨我试图从我的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;
}

2 个答案:

答案 0 :(得分: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", ipv4);
        }
    }
}

答案 1 :(得分:0)

使用带有getnameinfoNI_NUMERICHOST标记的NI_NUMERICSERV来获取表示主机和端口的数字形式字符串。