简体   繁体   中英

How to get IP addresses from sockaddr

Hi everyone
I was trying to get the IP addresses from my res struct but I still can't get through it, has anyone any idea how can I get them?

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;
}

IP addresses are stored in ai_addr field. You can use inet_ntop to get the ip address, like this:

#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);
        }
    }
}

使用带有NI_NUMERICHOSTNI_NUMERICSERV标志的getnameinfo来获取表示主机和端口的数字形式的字符串。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM