3
我想檢查網絡設備狀態,例如promiscous模式。基本上如ip a命令所示。如何檢查C中的網絡設備狀態?
也許有人能把我推向正確的方向?
我想在C中爲linux做這個工作,所以linux特定的頭文件可用。
我想檢查網絡設備狀態,例如promiscous模式。基本上如ip a命令所示。如何檢查C中的網絡設備狀態?
也許有人能把我推向正確的方向?
我想在C中爲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);
那就是它。謝謝 – 2010-06-16 19:14:14