C语言检测连接网卡状态

c语言之windows下判断网络是否连接(亲测可用) 【代码】c语言之windows下判断网络是否连接(亲测可用) 阅读详情

C语言检测连接网卡状态

​ 有些客户程序里面的代码需要自己检测网卡状态,检查是否连接网线。需要提供函数给他们调用,检测网卡连接状态。

//在<linux/ethtool.h>头文件中存在结构体`ethtool_value`,用于存放网卡连接状态。
/* for passing single values */
struct ethtool_value {
        __u32   cmd;
        __u32   data; // 表示网卡连接状态。
};

// 在<linux/sockios.h> 中存在
#define SIOCETHTOOL 0x8946   /* Ethtool interface    */

​ 函数如下,获取网卡连接状态。

/**
* if_name 值如"eth0". 
* 返回值:
* -1 表示 error 
* 1 表示 eth0 link up
* 0 表示 eth0 link down.
*/
int get_netlink_status(const char *if_name)
{
  int skfd;
  struct ifreq ifr;
  struct ethtool_value edata; // 用于获取网卡状态
  edata.cmd = ETHTOOL_GLINK;
  edata.data = 0;//网卡link状态值,0表示down,1表示up
  memset(&ifr, 0, sizeof(ifr));
  strncpy(ifr.ifr_name, if_name, sizeof(ifr.ifr_name) - 1);
  ifr.ifr_data = (char *) &edata;
  if (( skfd = socket( AF_INET, SOCK_DGRAM, 0 )) == 0){
      return -1;
  }
    
  if(ioctl( skfd, SIOCETHTOOL, &ifr ) == -1){
    close(skfd);
    return -1;
  }
  close(skfd);
  return edata.data;
}

测试案例

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <linux/if.h>

#include <linux/sockios.h>
#include <linux/ethtool.h>

/*获取网卡连接状态函数*/
int get_netlink_status(const char *if_name)
{
  int skfd;
  struct ifreq ifr;
  struct ethtool_value edata;
  edata.cmd = ETHTOOL_GLINK;
  edata.data = 0;
  memset(&ifr, 0, sizeof(ifr));
  strncpy(ifr.ifr_name, if_name, sizeof(ifr.ifr_name) - 1);
  ifr.ifr_data = (char *) &edata;
  if (( skfd = socket( AF_INET, SOCK_DGRAM, 0 )) == 0)
    return -1;
  if(ioctl( skfd, SIOCETHTOOL, &ifr ) == -1)
  {
    close(skfd);
    return -1;
  }
  close(skfd);
  return edata.data;
}

/*main */
int main(int argc, char* argv[])
{
 if(argc != 2) 
 {
       fprintf(stderr, "usage: %s <ethname>", argv[0]);
   return -1;
  }
  if(getuid() != 0)
  {
    fprintf(stderr, "请使用root权限.\n");
    return 1;
  }

  printf("Net link status: %s\n", get_netlink_status(argv[1]) == 1?"up":"down");
  return 0;
}

​ enp5s0f0接了网线,enp5s0f1没有接网线。
在这里插入图片描述

C语言实现检测Linux网络状态(附完整源码) 阅读详情

相关推荐

C语言实现linux网卡检测改进版

主要为大家详细介绍了C语言实现linux网卡检测的改进版,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

写一个检测网线是否被拔出的守护进程(嵌入式设备上)

#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <signal.h> #include <sys/file.h> #include <netinet/in.h> #include <linux/if.h> #include &l...

ws1296931325的博客 809

C#实战:手把手教你用SerialPort实现RS485 ModbusRTU通信(附完整代码)

本文详细介绍了如何使用C#的SerialPort类实现RS485 ModbusRTU通信,包括硬件准备、串口配置、数据收发核心逻辑及高级通信技巧。通过实战案例和完整代码,帮助开发者快速掌握工业级通信框架的构建方法,提升设备间通信的稳定性和效率。

weixin_29207533的博客 255

linux设置网卡采集模式,参考ethtool写了个Linux设置、获取网卡模式的接口

差不多一个月没写文章了,这期间,主要是搞一些比较复杂的问题,一直被搞,没有搞其它的东西,也就没写出什么东西来。在找问题过程中,上网了解到ethtool这个工具十分强大,以为这个代码很复杂,而恰好领导要求我提供设置网卡信息的接口,于是下了代码,研究了一下,参考了一下,整理了一下。当然文中写的是第一个版本,要是这样的接口提供出去,其它部门的人肯定会有意见的。Linux内核很早就已经加入ethtool相...

weixin_29323551的博客 887

中科蓝讯蓝牙耳机SDK实战:从目录解析到消息处理框架

本文深入解析中科蓝讯蓝牙耳机SDK的目录结构与消息处理框架,提供从硬件驱动到蓝牙功能定制的实战指南。重点剖析SDK核心模块如消息队列机制、按键事件处理及电量报告优化,并分享二次开发中的调试技巧与避坑经验,助力开发者高效完成TWS耳机功能定制。

weixin_30335575的博客 388

Vmware虚拟机一打开就蓝屏解决方法

Vmware虚拟机一打开就蓝屏解决方法 问题: 一打开Vmware虚拟机就蓝屏,如下图所示: 解决方法1: 启用和关闭windows功能(对话框)——>虚拟机平台(选项打对勾,默认没勾选)——>确定后重启——>再进应该就好了。 解决方法2: ①.查看电脑中的Hyper-V服务是否关闭 1.打开控制面板-程序-程序和功能 2.双击启用或关闭Windows功能 3.把Hyper-V前面的勾去掉 如果后期发下没有反应,或者电脑本身Hyper-V的服务没有打开,可以先打开在关闭,试

m0_55901666的博客 26万+

C语言检测网卡连接状态:sysfs、ioctl与netlink方案详解

在Linux系统编程中,获取网络接口的链路状态是嵌入式、网关及后台服务的常见需求。其核心原理是通过内核暴露的接口读取网卡的operstate、carrier等标志,判断物理链路是否连通。常用技术包括sysfs文件读取、ioctl系统调用和netlink套接字,其中netlink支持实时监听状态变化。准确检测网卡状态能保障网络冗余切换、服务健康检查等场景的可靠性。本文围绕C语言检测连接网卡状态,对比了多种实现方案并给出可复用代码。

weixin_29174385的博客 162

Windows平台MuJoCo仿真环境配置与Qt集成实战

本文详细介绍了在Windows平台上配置MuJoCo物理仿真环境并与Qt框架集成的完整实战流程。内容涵盖从环境准备、库文件配置、项目创建到核心代码编写的每一步,重点解决了Windows下常见的编译链接错误和路径问题,帮助开发者在Windows系统中高效搭建机器人仿真与可视化控制开发环境。

weixin_29221753的博客 172

linux c 网络连接检测,C语言实现linux网卡连接检测的方法

本文实例为大家分享了C语言实现linux网卡连接检测的具体代码,供大家参考,具体内容如下直接上代码吧#include #include #include #include #include #include #include #include #include #include int get_if_miireg(const char *if_name, int phy_id, int reg_n...

weixin_33204286的博客 719

StarCCM+ 导入STL几何模型进行仿真

通过 Import Surface Mesh 的方法导入 STL 文件进行仿真

薛定谔的alpha狗 6129

基于51单片机的电子记分牌的设计

基于51单片机的电子记分牌的设计 电子记分牌基于51单片机的电子记分牌的设计摘要1 引言2 总体设计方案2.1 设计思路(1)设计要求(2)设计思路(3)设计方案2.3综合设计方框图(1)硬件设计框图(2)软件设计3 设计原理分析3.1 电源、复位、下载电路的设计(见图1、2、3)3.2 时钟电路的设计3.3 矩阵键盘电路的设计3.4 数码管显示电路设计4程序代码 摘要 本设计为电子记分牌设计,是以STC89C52芯片为核心,辅以必要电路设计进行的。用4位LED七段数码管显示比赛两方的分数(每方分数用2位

行走的皮卡丘 2037

socket断网检测 c语言 linux,C语言+shell 实现linux网卡状态检测  和 C语言实现linux网卡连接检测 2文的方法各有缺陷,比如有些系统执行ifconfig需要root权限,...

#include #include #include #include #include #include #include #include #include #include #include #include #include int cshell_netlink_status(char *if_name){char buffer[BUFSIZ];char cmd[100];FILE ...

weixin_39594080的博客 282

PCL 提取两片点云的非重叠部分【2025最新版】

PCL 提取两片点云的非重叠部分。博客长期更新,本文最近一次更新时间为:2025年9月1日。

点云侠的博客 36万+

Linux下用程序检测网卡连通状态

在Linux下使用ifconfigl命令能很方便的查看网卡与网线是否连通,运行ifconfig eth0命令大致输出如下: # ifconfig eth0 eth0      Link encap:Ethernet  HWaddr 00:25:35:68:CC:D6             inet addr:192.168.1.168  Bcast:192.168.1.255  Mask:

学历只能代表过去,能力代表着现在,而学习代表的是未来。 997

AgentScope实战训练营- Java从零开始快速构建Agent完整教程

本文基于阿里巴巴开源的 AgentScope Java 框架,从零开始手把手带你构建 AI 智能体应用。内容涵盖环境搭建、基础对话、工具调用、结构化输出、多Agent流水线、Hook可观测性、会话持久化、MCP协议、RAG知识库集成、多模态工具、技能系统、Spring Boot Web部署等21个核心模块,附带完整可运行代码示例,帮助Java开发者快速掌握Agent开发全流程。

program哲学 863

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

C语言linux网口状态检测

C语言linux网口状态检测1.C语言+shell实现linux网卡状态检测2.C语言实现linux网卡连接检测的方法3.C语言实现linux网卡检测改进版4.C语言实现linux网卡检测精简版5.demo6.参考链接 1.C语言+shell实现linux网卡状态检测 直接上代码 要求linux环境具备grep和awk(awk可选) #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include &l

qq_27182175的博客 2775

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

shell 判断网线插拔_Linux下检测网卡与网线连通状态

在项目中和网络连接的模块中,要不停的去检查网络是否正常,尝试了很多的方法,最后终于找到了一个比较靠谱的方法,现在分享给大家。#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #in...

weixin_42363854的博客 736

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Linux主备网卡检测脚本,C语言+shell实现linux网卡状态检测

C语言+shell实现linux网卡状态检测发布时间:2020-08-20 17:26:57来源:脚本之家阅读:118作者:handyhuang本文实例为大家分享了C语言+shell实现linux网卡状态检测的具体代码,供大家参考,具体内容如下不解释,直接上代码 要求linux环境具备grep和awk(awk可选)#include #include #include #include int ge...

weixin_35916663的博客 450

C语言实现linux网卡连接检测

直接上代码吧 #include #include #include #include #include #include #include #include #include #include int get_if_miireg(const char *if_name, int phy_id, int reg_num ) { int

handyhuang的专栏 4164

Linux主备网卡检测脚本,C语言实现linux网卡连接检测的方法

本文实例为大家分享了C语言实现linux网卡连接检测的具体代码,供大家参考,具体内容如下直接上代码吧#include #include #include #include #include #include #include #include #include #include int get_if_miireg(const char *if_name, int phy_id, int reg_n...

weixin_36199877的博客 215

linux c语言实现启动禁用网卡,C语言实现linux网卡检测精简版

本文实例为大家分享了C语言实现linux网卡检测的精简代码,供大家参考,具体内容如下万能的网络,通过getifaddrs可以大大减少编码量,获得 C语言实现linux网卡检测-改进版 同样的效果。#include #include #include #include #include #include #include #include int c_ifaddrs_netlink_status(c...

weixin_34237362的博客 375

linux c语言实现启动禁用网卡,C语言+shell实现linux网卡状态检测

本文实例为大家分享了C语言+shell实现linux网卡状态检测的具体代码,供大家参考,具体内容如下不解释,直接上代码 要求linux环境具备grep和awk(awk可选)#include #include #include #include int get_if_status(char *if_name){char buffer[BUFSIZ];char cmd[100];FILE *re...

weixin_39705850的博客 286

linux 怎么看网卡状态,Linux下检测网卡与网线连通状态

在Linux下使用ifconfigl命令能很方便的查看网卡与网线是否连通,运行ifconfig eth0命令大致输出如下:# ifconfig eth0eth0 Link encap:Ethernet HWaddr 00:25:35:68:CC:D6inet addr:192.168.1.168 Bcast:192.168.1.255 Mask:255.255.255.0inet6...

weixin_39947908的博客 1297
上一篇: gcc与glibc关系
下一篇: Linux的Python文件的开头/usr/bin/env python与/usr/bin/python
elimuzi
博客等级 码龄10年 56粉丝 113原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值