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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With