如何检查以太网Linux呢? [英] How to check Ethernet in Linux?

查看:220
本文介绍了如何检查以太网Linux呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用C code,检查的eth0 需要在Linux中测试用例以太网。如果的eth0 下跌,我们能够那么净检查和测试通过。

I need the test case for Ethernet in Linux using C code to check eth0. If eth0 is down, we enable the net then check if up and the test is passed.

推荐答案

要检查链接起来,尝试这样的事情。它的工作原理没有root权限。

To check if the link is up, try something like this. It works without root privileges.

#include <stdio.h>        // printf
#include <string.h>       // strncpy
//#include <sys/socket.h> // AF_INET
#include <sys/ioctl.h>    // SIOCGIFFLAGS
#include <errno.h>        // errno
#include <netinet/in.h>   // IPPROTO_IP
#include <net/if.h>       // IFF_*, ifreq

#define ERROR(fmt, ...) do { printf(fmt, __VA_ARGS__); return -1; } while(0)

int CheckLink(char *ifname) {
    int state = -1;
    int socId = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
    if (socId < 0) ERROR("Socket failed. Errno = %d\n", errno);

    struct ifreq if_req;
    (void) strncpy(if_req.ifr_name, ifname, sizeof(if_req.ifr_name));
    int rv = ioctl(socId, SIOCGIFFLAGS, &if_req);
    close(socId);

    if ( rv == -1) ERROR("Ioctl failed. Errno = %d\n", errno);

    return (if_req.ifr_flags & IFF_UP) && (if_req.ifr_flags & IFF_RUNNING);
}

int main() {
    printf("%d\n", CheckLink("eth0"));
}

如果IFF_UP设置,这意味着接口(见ifup的)。如果设置了IFF_RUNNING然后接口堵塞。
我也尝试使用ethtool ioctl调用,但是失败了,当GID是不是根源。但是,仅仅日志:

If IFF_UP is set, it means interface is up (see ifup). If IFF_RUNNING is set then interface is plugged. I also tried using the ethtool ioctl call, but it failed when the gid was not root. But just for the log:

...
#include <asm/types.h>     // __u32
#include <linux/ethtool.h> // ETHTOOL_GLINK
#include <linux/sockios.h> // SIOCETHTOOL
...
int CheckLink(char *ifname) {
    ...
    struct ifreq if_req;
    (void) strncpy( if_req.ifr_name, ifname, sizeof(if_req.ifr_name) );

    struct ethtool_value edata;
    edata.cmd = ETHTOOL_GLINK;
    if_req.ifr_data = (char*) &edata;

    int rv = ioctl(socId, SIOCETHTOOL, &if_req);
    ...

    return !!edata.data;
}

这篇关于如何检查以太网Linux呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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