How can I get the IPv4 address of an interface on Linux from C code?
For example, I'd like to get the IP address (if any) assigned to eth0.
To get a detailed listing of all the IP-related characteristics of an interface, use the show ip interface command. A common use for this command is to view any secondary addresses that have been assigned to an interface (they do not show up in the standard show interface output).
Linux. Note: If hostname -I returns the IP both in IPv4 and IPv6 formats then you can use instead hostname -I | cut -f1 -d' ' to only show the IPv4 IP.
View All Network Interface Settings The “ifconfig” command with no arguments will display all the active interfaces details. The ifconfig command is also used to check the assigned IP address of a server.
Try this:
#include <stdio.h> #include <unistd.h> #include <string.h> /* for strncpy */ #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <netinet/in.h> #include <net/if.h> #include <arpa/inet.h> int main() { int fd; struct ifreq ifr; fd = socket(AF_INET, SOCK_DGRAM, 0); /* I want to get an IPv4 IP address */ ifr.ifr_addr.sa_family = AF_INET; /* I want IP address attached to "eth0" */ strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1); ioctl(fd, SIOCGIFADDR, &ifr); close(fd); /* display result */ printf("%s\n", inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr)); return 0; }
The code sample is taken from here.
In addition to the ioctl() method Filip demonstrated you can use getifaddrs(). There is an example program at the bottom of the man page.
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