#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#define PROC_NET_ROUTE "/proc/net/route"
int main() {
FILE *fp = fopen(PROC_NET_ROUTE, "r");
if (fp == NULL) {
perror("Error opening /proc/net/route");
return 1;
}
char line[256];
char iface[32];
char dest[32];
char gateway[32];
// 跳过第一行的标题
fgets(line, sizeof(line), fp);
while (fgets(line, sizeof(line), fp) != NULL) {
sscanf(line, "%s %s %s", iface, dest, gateway);
// 检查是否是默认路由
if (strcmp(dest, "00000000") == 0) {
unsigned long gw;
sscanf(gateway, "%lx", &gw);
struct in_addr gw_addr;
gw_addr.s_addr = gw;
printf("Default gateway IP: %s\n", inet_ntoa(gw_addr));
break;
}
}
fclose(fp);
return 0;
}
//很简单