Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get to know the IP address for interfaces in C?

Let's say I'm running a program called IpAddresses.c. I want that program to get all IP addresses this device has according to each interface. Just like ifconfig. How can I do that?

I don't know much about ioctl, but I read it might help me.

like image 418
gvalero87 Avatar asked Nov 09 '10 22:11

gvalero87


People also ask

Do interfaces have IP addresses?

Each network interface must have its own unique IP address. The IP address that you give to a host is assigned to its network interface, sometimes referred to as the primary network interface. If you add a second network interface to a machine, it must have its own unique IP number.

How do I find my interface details?

Use the ifconfig command to determine basic information about the interfaces of a particular system. For example, a simple ifconfig query can tell you the following: Device names of all interfaces on a system. All IPv4 and, if applicable, all IPv6 addresses that are assigned to the interfaces.


1 Answers

Just use getifaddrs(). Here's an example:

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

int main ()
{
    struct ifaddrs *ifap, *ifa;
    struct sockaddr_in *sa;
    char *addr;

    getifaddrs (&ifap);
    for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
        if (ifa->ifa_addr && ifa->ifa_addr->sa_family==AF_INET) {
            sa = (struct sockaddr_in *) ifa->ifa_addr;
            addr = inet_ntoa(sa->sin_addr);
            printf("Interface: %s\tAddress: %s\n", ifa->ifa_name, addr);
        }
    }

    freeifaddrs(ifap);
    return 0;
}

And here's the output I get on my machine:

Interface: lo   Address: 127.0.0.1
Interface: eth0 Address: 69.72.234.7
Interface: eth0:1       Address: 10.207.9.3
like image 180
chrisaycock Avatar answered Oct 20 '22 01:10

chrisaycock