getifaddrs函数的用法

2021-02-04, updated 2021-09-12

getifaddrs

获取linux ip地址方法,可以获取相应接口的ipv4和ipv6地址

ifaddrs

struct ifaddrs {        
    struct ifaddrs   *ifa_next;         /* Pointer to next struct */
    char             *ifa_name;         /* Interface name */
    u_int             ifa_flags;        /* Interface flags */
    struct sockaddr  *ifa_addr;         /* Interface address */
    struct sockaddr  *ifa_netmask;      /* Interface netmask */
    struct sockaddr  *ifa_dstaddr;      /* P2P interface destination */
    void             *ifa_data;         /* Address specific data */
};
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <string.h>

int main()
{
    struct ifaddrs *ifaddr, *ifa;
    struct sockaddr_in6 list;
    struct sockaddr_in6 mask;
    struct sockaddr_in6 prefix;
    char ip_str[64];

    if(-1 == getifaddrs(&ifaddr)) {
        printf("getifaddrs error\n");
        return -1;
    }

    ifa = ifaddr;
    int i = 0;

    while(ifa) {
        if(strcmp(ifa->ifa_name, "en0") == 0 && ifa->ifa_addr->sa_family == AF_INET6) {
            printf("ifa_name:%s ifa_flags:0x%x inet:%x\n", ifa->ifa_name, ifa->ifa_flags, ifa->ifa_addr->sa_family);
            memcpy(&list, ifa->ifa_addr, sizeof(struct sockaddr_in6));
            inet_ntop(AF_INET6, &list.sin6_addr, ip_str, sizeof(ip_str));
            printf("ip:%s\n", ip_str);
            for(i=0;i < 4;i ++) {
                printf("%x ", list.sin6_addr.__u6_addr.__u6_addr32[i]);
                // printf("%x ", list.sin6_addr.__in6_u.__u6_addr32[i]);
            }
            printf("\n");
            memcpy(&mask, ifa->ifa_netmask, sizeof(struct sockaddr_in6));
            inet_ntop(AF_INET6, &mask.sin6_addr, ip_str, sizeof(ip_str));
            printf("mask:%s\n", ip_str);

            for(i = 0;i < 16;i ++) {
                prefix.sin6_addr.__u6_addr.__u6_addr8[i] = list.sin6_addr.__u6_addr.__u6_addr8[i] & mask.sin6_addr.__u6_addr.__u6_addr8[i];
                // printf("prefix:%x list:%x mask:%x\n", prefix.sin6_addr.__u6_addr.__u6_addr8[i],list.sin6_addr.__u6_addr.__u6_addr8[i],mask.sin6_addr.__u6_addr.__u6_addr8[i]);
            }

            // memcpy(&prefix, ifa->ifa_netmask, sizeof(struct sockaddr_in6));
            inet_ntop(AF_INET6, &prefix.sin6_addr, ip_str, sizeof(ip_str));
            printf("prefix:%s\n", ip_str);
            
        }
        ifa = ifa->ifa_next;
    }


    freeifaddrs(ifaddr);
    return 0;
}

words: 220 tags: c