问题
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