Linux下c语言获取路由接口--思路

本文介绍了在Linux系统中如何通过/proc/net/route文件读取路由列表,以及利用structrtentry结构体和ioctl函数进行路由设置。主要涉及的函数有bb_displayroutes用于显示路由,INET_setroute用于添加或删除路由。涉及到的系统调用包括SIOCADDRT、SIOCDELRT和SIOCRTMSG。示例代码包含了必要的头文件和结构体定义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于读取路由列表,可以通过 /proc/net/route文件进行读取具体如何读取可以参考,busybox中的函数。

void FAST_FUNC bb_displayroutes(int noresolve, int netstatfmt);

对于设置,需要使用 struct rtentry配合ioctrl,可以参考busybox的函数。

static NOINLINE void INET_setroute(int action, char **args);
#include <sys/socket.h>
#include <linux/route.h>
#include <sys/ioctl.h>
#include <linux/if.h>
#include <linux/if_arp.h>
#include <netinet/in.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#define SIOCADDRT	0x890B		/* add routing table entry	*/
#define SIOCDELRT	0x890C		/* delete routing table entry	*/
#define SIOCRTMSG	0x890D		/* call to routing system	*/
struct rtentry {
	unsigned long	rt_pad1;
	struct sockaddr	rt_dst;		/* target address		*/
	struct sockaddr	rt_gateway;	/* gateway addr (RTF_GATEWAY)	*/
	struct sockaddr	rt_genmask;	/* target network mask (IP)	*/
	unsigned short	rt_flags;
	short		rt_pad2;
	unsigned long	rt_pad3;
	void		*rt_pad4;
	short		rt_metric;	/* +1 for binary compatibility!	*/
	char *rt_dev;	/* forcing the device at add	*/
	unsigned long	rt_mtu;		/* per route MTU/Window 	*/
#define rt_mss	rt_mtu			/* Compatibility :-(            */
	unsigned long	rt_window;	/* Window clamping 		*/
	unsigned short	rt_irtt;	/* Initial RTT			*/
};

http://www.cocoachina.com/articles/105156
https://stackoverflow.com/questions/17648440/specify-interface-when-adding-default-gateway-via-siocaddrt

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值