HOWTO检查在C网设备的状态? [英] howto check a network devices status in C?

查看:130
本文介绍了HOWTO检查在C网设备的状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查网络设备的状态如混杂模式。基本上像显示是 IP一个命令。

I would like to check a network devices status e.g. promiscous mode. Basically like shown with ip a command.

也许有人可以把我在正确的方向?

Maybe someone could push me in the right direction?

我要为Linux做这在C因此Linux特定的头文件是可用的。

I want to do this in C for linux so linux specific headers are available.

推荐答案

您需要使用 SIOCGIFFLAGS 的ioctl检索与接口关联的标志。然后,您可以检查 IFF_PROMISC 标志设置:

You need to use the SIOCGIFFLAGS ioctl to retrieve the flags associated with an interface. You can then check if the IFF_PROMISC flag is set:

#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(&ethreq, 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, &ethreq);
    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:

If you want to set the interface to promiscuous mode, you will need root privileges, but you can simply set the field in ifr_flags and use the SIOCSIFFLAGS ioctl:

/* ... */
ethreq.ifr_flags |= IFF_PROMISC;
ioctl(fd, SIOCSIFFLAGS, &ethreq);

这篇关于HOWTO检查在C网设备的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆