Linux 获取网关地址
2024-10-16 08:18:54
route命令的用法:操作或者显示IP路由表
route:DESCRIPTION
Route manipulates the kernel's IP routing tables. Its primary use is to set up static routes to
specific hosts or networks via an interface after it has been configured with the ifconfig(8) pro‐gram.
When the add or del options are used, route modifies the routing tables. Without these options,
route displays the current contents of the routing tables.
route-n:(用于打印路由表)
show numerical addresses instead of trying to determine symbolic host names. This is useful
if you are trying to determine why the route to your nameserver has vanished.
一、在Linux下查看路由表:
(1)用命令route -n
root@Ubunut10:~# route -n 内核 IP 路由表 目标 网关 子网掩码 标志 跃点 引用 使用 接口 eth1 eth1
(2)cat /pro/net/route
root@Ubunut10:/proc/net# cat route Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT eth1 007BA8C0 00FFFFFF eth1 FE7BA8C0
二、实现代码:
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <ctype.h> #include <signal.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <arpa/inet.h> int get_gateway_addr(char *gateway_addr) { ]; ; struct in_addr gw; int flgs, ref, use, metric; unsigned long int d,g,m; unsigned long addr; FILE *fp = NULL; fp = fopen("/proc/net/route", "r"); if (fp == NULL) { ; } nl = ; memset(buff, ,sizeof(buff)); while( fgets(buff, sizeof(buff), fp) != NULL ) { if(nl) { ; while(buff[ifl]!=' ' && buff[ifl]!='\t' && buff[ifl]!='\0') ifl++; buff[ifl]=; /* interface */ , "%lx%lx%X%d%d%d%lx", &d, &g, &flgs, &) { fclose(fp); ; } ifl = ; /* parse flags */ //if(flgs&RTF_UP) //{ gw.s_addr = g; ) { strcpy(gateway_addr, inet_ntoa(gw)); fclose(fp); ; } //} } nl++; } if(fp) { fclose(fp); fp = NULL; } ; } int main() { ] = {}; get_gateway_addr(gateway_addr); printf("gateway_addr:%s\n", gateway_addr); ; }
三、运行结果:
gateway_addr:192.168.123.254
最新文章
- 前端面试题 之 JavaScript
- Redis认识
- (转)C# 使用BackgroundWorker
- 【MVC】ASP.NET MVC 请求生命周期
- 乐在其中设计模式(C#) - 单例模式(Singleton Pattern)【转】
- 主流智能手机屏幕材质介绍 及 LCD闪屏现象分析
- js获取时间和日期,字符串和时间戳之间的转换
- samba连接提示“找不到网络路径”
- 最简单易懂的webService客户端之soap+xml请求
- centos free详解
- python315题
- Codeforces.835E.The penguin&#39;s game(交互 按位统计 二分)
- 【jquery】图片前后对比效果——beforeAfter
- 微信JS-SDK官方示例程序
- [BZOJ3669]魔法森林
- 数据链路层、ARP/RARP、ICMP、ping和traceroute
- protobuf与json转换
- Navigator - BOM对象
- Java集合类总结 (一)
- php 的基本语法