Get index of network interface

假如想象 提交于 2019-12-23 16:26:35

问题


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

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


回答1:


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



回答2:


Adding #include <sys/ioctl.h> on top of your code would solve your problem!



来源:https://stackoverflow.com/questions/41529934/get-index-of-network-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!