我想检查一个networking设备状态,例如promiscous模式。 基本上像ip显示一个命令。
也许有人能把我推向正确的方向?
我想在Linux中做这个,所以linux特定的头文件可用。
您需要使用SIOCGIFFLAGS
ioctl来检索与接口关联的标志。 然后您可以检查是否设置了IFF_PROMISC
标志:
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/ioctl.h> /* ioctl() */ #include <sys/socket.h> /* socket() */ #include <arpa/inet.h> #include <unistd.h> /* close() */ #include <linux/if.h> /* struct ifreq */ int main(int argc, char* argv[]) { /* this socket doesn't really matter, we just need a descriptor * to perform the ioctl on */ int fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); struct ifreq ethreq; memset(ðreq, 0, sizeof(ethreq)); /* set the name of the interface we wish to check */ strncpy(ethreq.ifr_name, "eth0", IFNAMSIZ); /* grab flags associated with this interface */ ioctl(fd, SIOCGIFFLAGS, ðreq); if (ethreq.ifr_flags & IFF_PROMISC) { printf("%s is in promiscuous mode\n", ethreq.ifr_name); } else { printf("%s is NOT in promiscuous mode\n", ethreq.ifr_name); } close(fd); return 0; }
如果要将界面设置为混杂模式,则需要root权限,但只需在ifr_flags
设置该字段并使用SIOCSIFFLAGS
ioctl:
/* ... */ ethreq.ifr_flags |= IFF_PROMISC; ioctl(fd, SIOCSIFFLAGS, ðreq);