加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

通过Linux中的SIOCGIFCONF轮询接口名称

发布时间:2020-12-13 23:01:06 所属栏目:Linux 来源:网络整理
导读:我正在尝试轮询网络设备名称.我从各种片段拼凑出来, http://unixhelp.ed.ac.uk/CGI/man-cgi?netdevice+7 http://lists.apple.com/archives/Unix-porting/2002/Apr/msg00134.html http://ubuntuforums.org/showthread.php?t=1421487 但我的输出只是胡言乱语.
我正在尝试轮询网络设备名称.我从各种片段拼凑出来,

> http://unixhelp.ed.ac.uk/CGI/man-cgi?netdevice+7
> http://lists.apple.com/archives/Unix-porting/2002/Apr/msg00134.html
> http://ubuntuforums.org/showthread.php?t=1421487

但我的输出只是胡言乱语.

#include <stdio.h>
#include <stdlib.h>
#include <net/route.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>

#define BUFLEN 1024
#define SEQ 9999

int main (int argc,const char* argv[])
{
  // File descriptor for socket
  int socketfd;
  struct ifconf conf;
  struct ifreq req[10];
  struct ifreq *ifr;

  printf("Opening socket...");
  socketfd = socket(AF_ROUTE,SOCK_RAW,0);
  if (socketfd >= 0) {
    printf(" OKn");
    conf.ifc_len = sizeof(req);
    conf.ifc_buf = (__caddr_t) req;
    ioctl(socketfd,SIOCGIFCONF,&conf);

    printf("Discovering interfaces...n");
    int i;
    for (i=0; i<conf.ifc_len/sizeof(req[0]); i++) {
      ifr = &conf.ifc_req[i];
      printf("%d. %sn",i+1,req[i].ifr_name);
    }
  }
  else {
    printf("Failed!n");
  }
  return 0;
}

输出:

Opening socket... OK
Discovering interfaces...
?u???}??Gh???
2. p?9}?
3.
4. v?=?n??u?`?y??]g?<?~?v??
5.
6.
7.
8. ?v?T?
9. ?|?mw??j??v??h??|??v?T00~??v?$?|??|?@
10. T00~??v?$?|??|?@

我尝试逐个输出ifr_name数组的每个char,看看它们是否为空终止但是没有太大变化.我的程序的每次迭代输出不同的东西,所以这让我觉得我引用了一些错误的东西.有人能为我提供一些有关我可能做错的见解吗?

解决方法

有关如何获取Linux上的接口列表,请参阅 http://git.netfilter.org/cgi-bin/gitweb.cgi?p=libmnl.git;a=blob;f=examples/rtnl/rtnl-link-dump.c;hb=HEAD. AF_ROUTE是一些BSD的东西,并且在Linux上不鼓励使用ioctl,因为它有明显的局限性(例如在单个接口上传送多个地址).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读