codingfreak codingfreak - 3 months ago 14
C Question

C code to get the IP address

How do I get the IP address of the local machine using C code?

If there are multiple Interfaces then I should be able to display the IP address of each interface.

NOTE: Do not use any commands like ifconfig within C code to retrieve the IP address.

Answer

With the inputs from Michael Foukarakis I am able to show the IP address for various interfaces on the same machine:

#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int
main(int argc, char *argv[])
{
    struct ifaddrs *ifaddr, *ifa;
    int family, s;
    char host[NI_MAXHOST];

    if (getifaddrs(&ifaddr) == -1) {
        perror("getifaddrs");
        exit(EXIT_FAILURE);
    }

    for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
        family = ifa->ifa_addr->sa_family;

        if (family == AF_INET) {
            s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in),
                                           host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
            if (s != 0) {
                printf("getnameinfo() failed: %s\n", gai_strerror(s));
                exit(EXIT_FAILURE);
            }
            printf("<Interface>: %s \t <Address> %s\n", ifa->ifa_name, host);
        }
    }
    return 0;
}