用ioctl获得本地ip地址,ifconf和ifreq

ifconf 和 ifreq 结构体 1.  ifreq /* * Interface request structure used for socket * ioctl's. All interface ioctl's must have parameter * definitions which begin with ifr_name. The * remainder may be interface specifi 阅读详情
用ioctl获得本地ip地址时要用到两个结构体ifconf和ifreq,它们对于大多数人
来说都是比较陌生的,这里给大家一种比较简单的理解方法,当然只一种帮助
理解的方法,在描述中可能会有一些地方与真实定义有所出入,仅供参考.

首先先认识一下ifconf和ifreq:

//ifconf通常是用来保存所有接口信息的

 //if.h 
 struct ifconf
 {
 	int ifc_len;  
 	union
 	{
 		char *ifcu_buf;  
 		struct ifreq *ifcu_req;  
 	} ifc_ifcu;
 };
 #define ifc_buf ifc_ifcu.ifcu_buf  
 #define ifc_req ifc_ifcu.ifcu_req  
   
 //ifreq用来保存某个接口的信息 
 //if.h 
 struct ifreq {
 	char ifr_name[IFNAMSIZ];
 	union {
 		struct sockaddr ifru_addr;
 		struct sockaddr ifru_dstaddr;
 		struct sockaddr ifru_broadaddr;
 		short ifru_flags;
 		int ifru_metric;
 		caddr_t ifru_data;
 	} ifr_ifru;
 };
 #define ifr_addr ifr_ifru.ifru_addr
 #define ifr_dstaddr ifr_ifru.ifru_dstaddr
 #define ifr_broadaddr ifr_ifru.ifru_broadaddr

 

上边这两个结构看起来比较复杂,我们现在把它们简单化一些:
比如说现在我们向实现获得本地IP的功能。

我们的做法是:
1. 先通过ioctl获得本地所有接口的信息,并保存在ifconf中
2. 再从ifconf中取出每一个ifreq中表示ip地址的信息

具体使用时我们可以认为ifconf就有两个成员:
ifc_len 和 ifc_buf,
如图一所示:    

 

ifc_len:表示用来存放所有接口信息的缓冲区长度
ifc_buf:表示存放接口信息的缓冲区

所以我们需要在程序开始时对ifconf的ifc_led和ifc_buf进行初始化
接下来使用ioctl获取所有接口信息,完成后ifc_len内存放实际获得的借口信息总长度
并且信息被存放在ifc_buf中。

如下图示:(假设读到两个接口信息)

   

 

 

接下来我们只需要从一个一个的接口信息获取ip地址信息即可。

下面有一个简单的参考:

  #include <string.h>

 #include <net/if.h>
 #include <unistd.h>
 #include <sys/ioctl.h>
 
 #include <netinet/in.h>  
 
 
 
 
 
 
 int main()
 {
 	int i=0;
 	int sockfd;
 	struct ifconf ifconf;
 	unsigned char buf[512];
 	struct ifreq *ifreq;
 
 	//初始化ifconf 
 	ifconf.ifc_len = 512;
 	ifconf.ifc_buf = buf;
 
 	if((sockfd = socket(AF_INET, SOCK_DGRAM, 0))<0)
 	{
 		perror("socket");
 		exit(1);
 	}
 	ioctl(sockfd, SIOCGIFCONF, &ifconf); //获取所有接口信息 
 
 	//接下来一个一个的获取IP地址 
 	ifreq = (struct ifreq*)buf;
 	for(i=(ifconf.ifc_len/sizeof(struct ifreq)); i>0; i--)
 	{
 		// if(ifreq->ifr_flags == AF_INET){ //for ipv4 
 		printf("name = [%s]n", ifreq->ifr_name);
 		printf("local addr = [%s]n",
 		inet_ntoa(((struct sockaddr_in*)&(ifreq->ifr_addr))->sin_addr));
 		ifreq++;
 		// } 
 	}
 return 0;
 }

 

  
  
 
此方法仅供参考,也适用于获取其他信息。
详解struct ifreq ifr 以下是// 接口名称,如 "eth0" 或 "wlan0"union {// 用于存储地址// 用于存储硬件地址(MAC 地址)// 网络接口标志// 接口索引// 硬件映射,通常用于设置设备// 指定接口度量// 接口的最大传输单元// 接口配置,通常用于获取接口列表是一个多用途的数据结构,用于存储和操作网络接口的配置信息。它在使用ioctl系统调用时尤其重要,因为ioctl是与网络接口(如获取 IP 地址、MAC 地址、接口标志等)交互的一种常见方式。通过ifreq。 阅读详情

相关推荐

机械臂开发必备:KDL库正逆解与动力学实战指南

在机器人算法领域,运动学与动力学计算是机械臂控制、仿真与轨迹规划的核心基础。正运动学描述关节空间到笛卡尔空间的映射,逆运动学则需要求解复杂的非线性方程,工程实现时常面临数值稳定性与调试效率的挑战。KDL(Kinematics and Dynamics Library)作为ROS生态中广泛使用的开源库,提供了统一的模型描述与高效求解器,将正逆解、雅可比矩阵及动力学参数计算封装为简洁接口,大幅降低开发门槛。无论是机械臂的笛卡尔空间轨迹跟踪,还是基于动力学模型的前馈控制,KDL都展现出强大的工程价值。本文从运动学

weixin_33860528的博客 2506

struct ifreq学习和实例

一、struct ifreq结构体 这个结构定义在/usr/include/net/if.h,用来配置和获取ip地址,掩码,MTU等接口信息的。 /* Interface request structure used for socket ioctl's. All interface ioctl's must have parameter definitions which

Jalen_king 2万+

汇川H5U搭配步进伺服电机使用CANopen通讯控制电机案例

摘要:本文介绍了基于汇川H5U PLC和STM4260B-CANopen-M步进伺服电机的控制系统搭建流程。主要内容包括:硬件准备(PLC、伺服电机、24V电源)、电机参数默认设置(地址1号、1M波特率)、使用AutoShop软件编写程序(配置CANopen参数、导入电机描述文件、设置PDO参数)以及功能块编程(使能控制、速度控制、绝对位置控制等)。通过查阅通讯手册完成各功能块参数配置,最终在主程序中调用功能块实现控制系统开发。该方案适用于需要精确运动控制的工业自动化场景。

m0_46512607的博客 1596

Linux网络编程- struct ifreq & ioctl() 系统调用

是一个数据结构,用于各种与接口相关的输入/输出控制 (ioctl) 调用。它的主要用途是在网络编程中获取和设置网络接口的属性。这个结构体在头文件中定义。以下是: 一个字符数组,表示接口的名称,如 “eth0”, “wlan0” 等。: 一个类型的结构,表示接口的地址。: 同样是一个类型的结构,表示接口的网络掩码。: 表示接口的广播地址。: 表示接口的标志,如IFF_UP(接口正在运行)、(接口支持广播)、(接口在混杂模式下)等。: 表示接口的硬件(通常是 MAC)地址。

青衫客36的博客 6916

一篇讲透:豆包、元宝、DeepSeek、Kimi、WorkBuddy,职场里到底怎么分工

这篇文章深入分析了当前主流AI工具(WorkBuddy、豆包、腾讯元宝、DeepSeek、Kimi)的特点和使用场景,帮助读者根据不同工作需求选择合适的AI助手。核心观点包括: AI工具各有所长:豆包适合快速创作初稿,元宝擅长信息检索整理,DeepSeek强于逻辑分析,Kimi专精文本处理,WorkBuddy则更适合任务推进和成果交付。 使用前需明确需求:是要创意发散、信息整理,还是任务执行?不同阶段应选用不同工具组合。 提供了6个具体职场场景的解决方案,包括文章创作、课程设计、会议纪要等,并给出详细的操作

weixin_39284145的博客 1万+

coreldraw sp2精简版 x4_CorelDRAW X4下载-CorelDRAW X4 SP2 精简版_Win10镜像官网

CorelDRAW X4 SP2是一个专业图形设计软件,专用于矢量图形编辑与排版,借助其丰富的内容和专业图形设计、照片编辑和网站设计软件,您将能够随心所欲地表达自己的风格与创意,轻松创作徽标标志、广告标牌、车身贴和传单、模型绘制、插图描画、排版及分色输出等。CorelDRAW X4 SP2软件特色CorelDraw X4 相比两年前的 CorelDraw X3 加入了大量新特性,总计有50项以上,...

weixin_30346025的博客 8904

struct ifreq 的用法详解

ifreq结构定义在/usr/include/net/if.h,用来配置ip地址,激活接口,配置MTU等接口信息的。其中包含了一个接口的名字和具体内容——(是个共用体,有可能是IP地址,广播地址,子网掩码,MAC号,MTU或其他内容)。ifreq包含在ifconf结构中。而 ifconf结构通常是用来保存所有接口的信息的。

sin0803的专栏 2万+

Wio-LR1121多频段LoRa模块技术解析与应用实践

LoRa技术作为低功耗广域物联网(LPWAN)的核心通信方案,通过独特的扩频调制技术实现远距离传输与强抗干扰能力。其工作原理基于CSS(Chirp Spread Spectrum)调制,支持动态调整扩频因子(SF)和带宽(BW)来平衡传输距离与数据速率。Wio-LR1121模块作为Semtech LR1121芯片的载体,创新性地整合了sub-GHz、S-Band和2.4GHz多频段支持,配合仅1.35μA的睡眠电流,为跨境物联网部署提供了硬件基础。在智慧农业、工业监测等场景中,开发者可通过SPI接口快速集成

weixin_33742618的博客 416

ioctl和struct ifreq

用ioctl获得本地ip地址时要用到两个结构体ifconf和ifreq,它们对于大多数人来说都是比较陌生的,这里给大家一种比较简单的理解方法,当然只一种帮助理解的方法,在描述中可能会有一些地方与真实定义有所出入,仅供参考. 首先先认识一下ifconf和ifreq: //ifconf通常是用来保存所有接口信息的//if.hstruct

wl_haanel的专栏 1万+

开发Qt上位机获取阿里云IOT设备数据(开发上位机对接阿里云IOT平台)

使用Qt框架开发一款上位机软件,调用阿里云物联网平台的API接口,获取设备最新上传的实时数据,并在Qt设计的软件界面上展示处理。同时,还支持绘制曲线图表展示数据,并具备定时刷新功能。

2144

【数据湖仓】:Iceberg、Hudi 和 Paimon 对比

适用于需要多计算引擎支持和复杂查询的离线批处理场景。其中立性和灵活性使其成为构建新型数据平台的理想选择。:在需要高频数据更新和高效小文件管理的场景中表现出色,适合实时数据处理和增量数据更新的业务需求。:专为实时流式数据处理设计,适用于对数据实时性要求高的业务场景,如实时数据分析和实时指标监控。通过以上分析,可以看出 Apache Iceberg、Apache Hudi 和 Apache Paimon 各有其独特的优势和适用场景。企业应根据自身业务需求和技术栈选择合适的数据湖仓方案,以充分发挥其价值。

欢迎来到我的博客,一起探索代码里的世界! 1610

两个结构体 ifconf 和 ifreq

所以我们需要在程序开始时对ifconf的ifc_len和ifc_buf进行初始化,接下来使用ioctl获取所有接口信息,完成后ifc_len内存放实际获得的接口信息总长度并且信息被存放在ifc_buf中。用ioctl获得本地IP地址、MAC地址或者子网掩码时要用到两个结构体ifconf和ifreq,它们对于大多数人来说都是比较陌生的,这里给大家一种比较简单的理解方法,当然只一种帮助。ifc_len表示用来存放所有接口信息的缓冲区长度。......

布袋和尚 3295

瑞芯微RV1109平台GT911触摸屏驱动调试记录1

很明显这里可以看到系统已经配置了i2c-0、i2c-1、i2c-3、i2c-4、i2c-5,当开机的时候系统已经将相应的I2C节点注册成功了,说明I2C部分是没有问题的。

bingdund的博客 298

ifconf和ifreq

用ioctl获得本地ip地址时要用到两个结构体ifconf和ifreq,它们对于大多数人来说都是比较陌生的,这里给一种比较简单的理解方法, 仅供参考. 首先先认识一下ifconf和ifreq: //ifconf通常是用来保存所有接口信息的 //ifreq用来保存某个接口的信息 //if.h struct ifreq { char ifr_name[IFNAMSIZ];

jasenwan88的专栏 4303

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

两个结构体ifconf和ifreq

用ioctl获得本地ip地址时要用到两个结构体ifconf和ifreq,它们对于大多数人 来说都是比较陌生的,这里给大家一种比较简单的理解方法,当然只一种帮助 理解的方法,在描述中可能会有一些地方与真实定义有所出入,仅供参考. 首先先认识一下ifconf和ifreq: //ifconf通常是用来保存所有接口信息的 //if.h struct ifconf {

liuqinstudy的专栏 6066

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

用ioctl获得本地ip地址

<br /><br />用ioctl获得本地ip地址时要用到两个结构体ifconf和ifreq,它们对于大多数人<br />来说都是比较陌生的,这里给大家一种比较简单的理解方法,当然只一种帮助<br />理解的方法,在描述中可能会有一些地方与真实定义有所出入,仅供参考.<br />首先先认识一下ifconf和ifreq://ifconf通常是用来保存所有接口信息的//if.hstruct ifconf {int ifc_len; /* size of buffer */

星愿心愿的专栏 1139

深度学习工具包 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")

UDP struct ifreq和struct ifconf获取IP地址

UDP struct ifreq和struct ifconf获取IP地址 (一)获得本地ip地址时要用到两个结构体ifconf和ifreq(#include /* * Interface request structure used for socket * ioctl's.All interface ioctl's must have parameter ifco

懒洋洋工程师的笔记 1526

linux获取本机IP地址的方法 struct ifconf

原文出自:  http://blog.sina.com.cn/s/blog_5d0e8d0d0101604k.html #include 其实你可以 >find /usr/include/ -name "*.h" -exec grep -l "ifconf" {} \;  (  grep  -l或--file-with-matches   列出文件内容符合指定的范本

hardccyy的专栏 2697

获取网络接口信息——ioctl()函数与结构体struct ifreq、 struct ifconf (获取或设置 网卡 IP 子网掩码 本地广播地址)

Linux 下 可以使用ioctl()函数 以及 结构体 struct ifreq 结构体struct ifconf来获取网络接口的各种信息。 ioctl 首先看ioctl()用法 ioctl()原型如下: #include <sys/ioctl.h> int ioctl(int fd, int request, ...); 参数: fd : 文件描述符 reque...

yyyljw的博客 697
上一篇: MSP430与GPRS模块的串口通信硬件流控制
下一篇: getsockopt/setsockopt函数说明(一)
tinyhare
博客等级 码龄15年 11粉丝 9原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值