linux获取系统默认网关,请用c语言写出程序
时间: 2024-03-10 18:48:49 浏览: 33
以下是获取系统默认网关的C语言程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#define MAX_IFS 64
int main() {
int sock;
char buf[8192];
struct ifconf ifconf;
struct ifreq ifreq[MAX_IFS];
int ifs, i;
struct sockaddr_in *sin;
// 创建套接字
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) {
perror("socket");
return 1;
}
// 获取接口列表
ifconf.ifc_len = sizeof(buf);
ifconf.ifc_buf = buf;
if (ioctl(sock, SIOCGIFCONF, &ifconf) < 0) {
perror("ioctl(SIOCGIFCONF)");
return 1;
}
// 遍历接口
ifs = ifconf.ifc_len / sizeof(struct ifreq);
for (i = 0; i < ifs; i++) {
sin = (struct sockaddr_in *)&ifreq[i].ifr_addr;
// 获取接口地址
if (ioctl(sock, SIOCGIFFLAGS, &ifreq[i]) < 0) {
perror("ioctl(SIOCGIFFLAGS)");
return 1;
}
// 排除本地回环接口
if ((ifreq[i].ifr_flags & IFF_LOOPBACK) != 0) {
continue;
}
// 获取默认网关
if (ioctl(sock, SIOCGIFDSTADDR, &ifreq[i]) < 0) {
perror("ioctl(SIOCGIFDSTADDR)");
return 1;
}
// 输出网关地址
printf("%s\n", inet_ntoa(sin->sin_addr));
}
return 0;
}
```
该程序使用了套接字的ioctl函数和系统调用SIOCGIFCONF、SIOCGIFFLAGS和SIOCGIFDSTADDR,通过遍历接口列表获取所有接口的网关地址,然后输出默认网关。