views:

505

answers:

3

On a Linux box, the common interface names look like eth0, eth1, etc. I know how to find at least one IP using gethostbyname or similar functions, but I don't know any way to specify which named interface I want the IP 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 IPs (and maybe MAC addresses) into a collection? Or at least something along the lines of gethostbyinterface("eth0")?

+1  A: 

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
phjr
+8  A: 

From TLUG:

#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;
 }
Walter
Of course there is one drawback: you open a dummy socket. Anyway, nice job.
phjr
A: 

See this question: Get the IP Address of local computer

camh