tags:

views:

592

answers:

3

How can I get the IPv4 address of an interface in linux from C code ?

e.g. I'd like to get the IP address(if any) assigned to eth0

+1  A: 

I found this page see if it has what you need.

rerun
+11  A: 

Try this:

#include <stdio.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>

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 take from here.

Filip Ekberg
+7  A: 

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

Duck
getifaddrs seems very comprehensive. Other methods will only give the primary or first address per interface.
MarkR
Oh awesome, never knew about this!
Matt Joiner