Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding an IP address from an interface name

On a Linux box, the common interface names look like eth0, eth1, etc. I know how to find at least one IP address using gethostbyname or similar functions, but I don't know any way to specify which named interface I want the IP address of. I could use ifconfig and parse the output, but shelling out for this information seems... inelegant.

Is there a way to, say, enumerate all the interfaces and their IP addresses (and maybe MAC addresses) into a collection? Or at least something along the lines of gethostbyinterface("eth0")?

like image 779
Coderer Avatar asked Nov 03 '08 17:11

Coderer


2 Answers

// Originally from http://www.tlug.org.za/wiki/index.php/Obtaining_your_own_IP_address

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>

/**
 * getIPv4()
 *
 * This function takes a network identifier such as "eth0" or "eth0:0" and
 * a pointer to a buffer of at least 16 bytes and then stores the IP of that
 * device gets stored in that buffer.
 *
 * it return 0 on success or -1 on failure.
 *
 * Author:  Jaco Kroon <[email protected]>
 */
int getIPv4(const char * dev, char * ipv4) {
    struct ifreq ifc;
    int res;
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);

    if(sockfd < 0)
        return -1;
    strcpy(ifc.ifr_name, dev);
    res = ioctl(sockfd, SIOCGIFADDR, &ifc);
    close(sockfd);
    if(res < 0)
        return -1;     
    strcpy(ipv4, inet_ntoa(((struct sockaddr_in*)&ifc.ifr_addr)->sin_addr));
    return 0;
}


int main() {
    char ip[16];
    if(getIPv4("eth0", ip) == 0)
        printf("IPv4: %s\n", ip);
    else
        printf("No IP\n");
    return 0;
 }

Update: Moved dead link to a comment (for posterity) (thanks @obayhan), and added syntax highlighting.

like image 180
Walter Avatar answered Sep 28 '22 06:09

Walter


edit: I saw you don't like shelling. Then you can look at how ifconfig does its job (it extracts at least some information from /proc).

When you have interface name, you can do this (in your shell):

ifconfig eth0 | grep 'inet addr' | sed -e 's/:/ /' | awk '{print $3}'

To enumerate interfaces you can use this:

ifconfig | egrep '^[^ ]' | awk '{print $1}'

Combined:

for x in `ifconfig | egrep '^[^ ]' | awk '{print $1}'`; do
  echo -n "${x}"
  echo -n "    "
  ifconfig "${x}" | grep 'inet addr' | sed -e 's/:/ /' | awk '{print $3}'
done
like image 22
Paweł Hajdan Avatar answered Sep 28 '22 05:09

Paweł Hajdan