从IP地址查找一个接口名称 [英] Finding an interface name from an IP address

查看:191
本文介绍了从IP地址查找一个接口名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过提供IP地址来获取接口名称。没有系统调用来得到这个。

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

我需要C或C ++本实施

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

已经是这个反向可在堆栈溢出,的 查找从接口名称的IP地址

Already the reverse of this is available on Stack Overflow, Finding an IP address from an interface name.

推荐答案

使用的 getifaddrs(3) 。简单的例子。用法./foo 123.45.67.89请添加错误检查等:

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;
}

这篇关于从IP地址查找一个接口名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆