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 测试。

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的示例代码,用于检测所有网口的 UP 和 DOWN 状态。该代码使用了 Netlink Socket API,需要在 Linux 系统中编译和运行。 ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #define BUFSIZE 8192 int main() { int fd; struct sockaddr_nl sa; char buf[BUFSIZE]; struct nlmsghdr *nh; struct ifinfomsg *ifinfo; int len; // 创建 Netlink Socket if ((fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE)) < 0) { perror("socket"); exit(1); } memset(&sa, 0, sizeof(sa)); sa.nl_family = AF_NETLINK; sa.nl_groups = RTMGRP_LINK; // 监听网卡变化事件 if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0) { perror("bind"); exit(1); } // 接收 Netlink 消息 while ((len = recv(fd, buf, BUFSIZE, 0)) > 0) { for (nh = (struct nlmsghdr *)buf; NLMSG_OK(nh, len); nh = NLMSG_NEXT(nh, len)) { if (nh->nlmsg_type == NLMSG_DONE) { break; } else if (nh->nlmsg_type == NLMSG_ERROR) { perror("recv"); exit(1); } else if (nh->nlmsg_type != RTM_NEWLINK) { continue; } ifinfo = (struct ifinfomsg *)NLMSG_DATA(nh); // 监听到网卡 UP 或 DOWN 事件 if (ifinfo->ifi_change & (IFACE_UP | IFACE_DOWN)) { printf("Interface %d is %s\n", ifinfo->ifi_index, (ifinfo->ifi_flags & IFF_UP) ? "UP" : "DOWN"); } } } close(fd); return 0; } ``` 该程序使用了 Netlink Socket API 监听 RTMGRP_LINK 组,对于每个 RTM_NEWLINK 消息,解析其中的 ifinfomsg 结构体,检查其 ifi_change 和 ifi_flags 成员以确定网卡 UP 或 DOWN 事件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值