获取网络接口索引 [英] Get index of network interface

查看:124
本文介绍了获取网络接口索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为C上的OS X编写简单的嗅探器 所以,我有一个问题,我无法获取网络接口的索引. 我使用以下代码:

I'm writing simple sniffer for OS X on C So, I have a problem, I can't get index of network interface. I use this code:

int sockfd=socket(PF_INET, SOCK_DGRAM, 0);
  if(sockfd<0)
  {
    printf("create socket");
    fprintf(stderr, "%s\n",strerror(errno));
    exit(EXIT_FAILURE);
  }
  sprintf( ifreq.ifr_name, "%s", "en0");
  if(ioctl(sockfd, SIOCGIFINDEX, &ifreq)<0) 
  {
    fprintf(stderr, "%s\n",strerror(errno));
    exit(EXIT_FAILURE);
  }

问题是未声明标识符"SIOCGIFINDEX". 如果我理解正确,则网络接口索引需要结构化sockaddr_ll

Problem that identifier 'SIOCGIFINDEX' is undeclared. Index of network interface need for structute sockaddr_ll , if I understand rightly

推荐答案

您也可以尝试看一下这段代码. 这将获得具有名称的界面,并对其进行处理. ifap 完成后,别忘了包含标题并释放内存.

You could also try and look at this code. This will get the interface with the name and do something with it. Don't forget to include the header and free the memory when you're done with ifap.

#include <ifaddrs.h>
void do_smth_with_interface(const char *name) 
{

    struct ifaddrs *ifap = NULL;

    if(getifaddrs(&ifap) < 0) {
        printf("Cannot get a list of interfaces\n");
        return;
    }

    for(struct ifaddrs *p = ifap; p!=NULL; p=p->ifa_next) {
        if (strcmp(p->ifa_name, name) == 0)
                // do smth with the interface.
    }

    freeifaddrs(ifap);
 }

这篇关于获取网络接口索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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