Cでネットワークデバイスのステータスを確認する方法は?
-
27-09-2019 - |
質問
ネットワークデバイスのステータスなどを確認したい場合があります。基本的に示されているように IP a 指図。
たぶん誰かが私を正しい方向に押すことができますか?
LinuxのためにCでこれを行いたいので、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;
}
あなたがしたい場合は セットする インターフェイスは無差別モードで、ルート特権が必要になりますが、フィールドをに設定することはできます。 ifr_flags
そして、使用します SIOCSIFFLAGS
ioctl:
/* ... */
ethreq.ifr_flags |= IFF_PROMISC;
ioctl(fd, SIOCSIFFLAGS, ðreq);
所属していません StackOverflow