tags:

views:

709

answers:

2

I need to get the interface name by providing ip address.There is no system call to get this.

I need an implementation for this in c or c++

Already thee reverse of this is available in this forum. http://stackoverflow.com/questions/259389/finding-an-ip-from-an-interface-name

+6  A: 

Could you simply parse the output from something like

 netstat -ie | grep -B1 "192.168.21.10"

The -B1 part tells grep we want to include the line before the match in the output, so we get this:

eth0      Link encap:Ethernet  HWaddr 00:13:72:79:65:23
          inet addr:192.168.21.10  Bcast:192.168.21.255  Mask:255.255.255.0

Once you have confidence you're getting the output you need, you can condense it further into a one-liner....

netstat -ie | grep -B1 "192.168.21.10" | head -n1 | awk '{print $1}'

which just returns "eth0"

Paul Dixon
i need to call a function from a c/c++ program
look at the source of netstat or ifconfig to see how it does it. Generally packaged with net-tools.
Paul Dixon
+2  A: 

Use getifaddrs(3). Simple example. Usage "./foo 123.45.67.89" Please add error checking etc:

#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <ifaddrs.h>

int main(int argc, char *argv[]) {
  struct ifaddrs *addrs, *iap;
  struct sockaddr_in *sa;
  char buf[32];

  getifaddrs(&addrs);
  for (iap = addrs; iap != NULL; iap = iap->ifa_next) {
    if (iap->ifa_addr && (iap->ifa_flags & IFF_UP) && iap->ifa_addr->sa_family == AF_INET) {
      sa = (struct sockaddr_in *)(iap->ifa_addr);
      inet_ntop(iap->ifa_addr->sa_family, (void *)&(sa->sin_addr), buf, sizeof(buf));
      if (!strcmp(argv[1], buf)) {
        printf("%s\n", iap->ifa_name);
      }
    }
  }
  freeifaddrs(addrs);
  return 0;
}
matli