mthoutai

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

linux c 获取网卡状态(UP or DOWN)

源代码例如以下:

#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/if.h>
#include <string.h>
#include <stdio.h>


char *net_detect(char* net_name)
{
        int skfd = 0;
        struct ifreq ifr;

        skfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(skfd < 0) {
                printf("%s:%d Open socket error!\n", __FILE__, __LINE__);
                return NULL;
        }

        strcpy(ifr.ifr_name, net_name);

        if(ioctl(skfd, SIOCGIFFLAGS, &ifr) <0 ) {
                printf("%s:%d IOCTL error!\n", __FILE__, __LINE__);
                printf("Maybe ethernet inferface %s is not valid!", ifr.ifr_name);
                close(skfd);
                return NULL;
        }

        if(ifr.ifr_flags & IFF_RUNNING) {
                return "UP";
        } else {
                return "DOWN";
        }

}
int main()
{
        printf("%s\n",net_detect("eth0"));
        return 0;
}

总结:
该程序是測试 ifconfig 命令中 指定网卡 是实用 RUNNING 。

能够配合 ifconfig eth0 up 和 ifconfig eth0 down 測试。

<script type="text/javascript"> $(function () { $('pre.prettyprint code').each(function () { var lines = $(this).text().split('\n').length; var $numbering = $('
    ').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($('
  • ').text(i)); }; $numbering.fadeIn(1700); }); }); </script>
---

相关学习推荐

根据本文内容,精选以下优质课程:

  1. 趣谈网络协议
    ‍ 刘超 | 轻松掌握网络协议核心原理
  2. C++实战笔记
    ‍ 罗剑锋 | 高效学习现代C++编程
  3. 趣谈Linux操作系统
    ‍ 刘超 | 轻松理解Linux操作系统核心原理

开发资源

posted on 2017-07-31 14:02  mthoutai  阅读(3021)  评论(0)    收藏  举报