Monday, February 6, 2017

[Linux] Get list of local IPv4 addresses in C++

#include <stdio.h>
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <net/if.h>

int main()
{
    struct ifaddrs* ifap;
    getifaddrs(&ifap);

    for (ifaddrs* ifa = ifap; ifa; ifa = ifa->ifa_next)
    {
        if ((AF_INET == ifa->ifa_addr->sa_family) && ((ifa->ifa_flags & IFF_UP) > 0) && (0 == (ifa->ifa_flags & IFF_LOOPBACK)))
        {
            struct sockaddr_in* sa = (struct sockaddr_in *) ifa->ifa_addr;
            char* addr = inet_ntoa(sa->sin_addr);
            printf("%s\n", addr);
        }
    }

    freeifaddrs(ifap);

    return 0;
}

No comments:

Post a Comment