Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get IP address of an interface on Linux

Tags:

c

linux

sockets

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.

like image 526
leeeroy Avatar asked Feb 17 '10 18:02

leeeroy


People also ask

How do I find my IP interface?

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).

How do I show IP address only in Linux?

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.

How can you display the IP assigned on a network interface?

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.


2 Answers

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.

like image 148
Filip Ekberg Avatar answered Oct 14 '22 09:10

Filip Ekberg


In addition to the ioctl() method Filip demonstrated you can use getifaddrs(). There is an example program at the bottom of the man page.

like image 37
Duck Avatar answered Oct 14 '22 10:10

Duck