通过RTM_GETROUTE 获取路由表,写出一个简单的测试程序,需要获取网关地址
时间: 2024-03-10 22:50:25 浏览: 123
简单的路由程序
好的,以下是一个简单的测试程序,它使用RTM_GETROUTE消息获取路由表中的网关地址,并输出到终端上。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <arpa/inet.h>
int main() {
int netlink_fd;
struct sockaddr_nl src_addr;
memset(&src_addr, 0, sizeof(src_addr));
src_addr.nl_family = AF_NETLINK;
if ((netlink_fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE)) < 0) {
perror("socket");
exit(EXIT_FAILURE);
}
if (bind(netlink_fd, (struct sockaddr *)&src_addr, sizeof(src_addr)) < 0) {
perror("bind");
close(netlink_fd);
exit(EXIT_FAILURE);
}
struct {
struct nlmsghdr nlh;
struct rtmsg rt;
} req;
memset(&req, 0, sizeof(req));
req.nlh.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
req.nlh.nlmsg_type = RTM_GETROUTE;
req.nlh.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP;
req.nlh.nlmsg_seq = 1;
req.rt.rtm_family = AF_INET;
req.rt.rtm_table = RT_TABLE_MAIN;
req.rt.rtm_protocol = RTPROT_UNSPEC;
struct msghdr msg;
struct iovec iov;
memset(&msg, 0, sizeof(msg));
memset(&iov, 0, sizeof(iov));
iov.iov_base = &req;
iov.iov_len = req.nlh.nlmsg_len;
msg.msg_name = &src_addr;
msg.msg_namelen = sizeof(src_addr);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
if (sendmsg(netlink_fd, &msg, 0) < 0) {
perror("sendmsg");
close(netlink_fd);
exit(EXIT_FAILURE);
}
char buf[4096];
struct nlmsghdr *nlh;
while (1) {
int len = recv(netlink_fd, buf, sizeof(buf), 0);
if (len < 0) {
perror("recv");
close(netlink_fd);
exit(EXIT_FAILURE);
}
for (nlh = (struct nlmsghdr *)buf; NLMSG_OK(nlh, len); nlh = NLMSG_NEXT(nlh, len)) {
if (nlh->nlmsg_type == NLMSG_ERROR) {
perror("NLMSG_ERROR");
close(netlink_fd);
exit(EXIT_FAILURE);
}
if (nlh->nlmsg_type == NLMSG_DONE)
break;
struct rtmsg *rtm;
struct rtattr *rta;
int rt_len;
rtm = (struct rtmsg *) NLMSG_DATA(nlh);
rt_len = nlh->nlmsg_len - NLMSG_LENGTH(sizeof(struct rtmsg));
for (rta = RTM_RTA(rtm); RTA_OK(rta, rt_len); rta = RTA_NEXT(rta, rt_len)) {
if (rta->rta_type == RTA_GATEWAY) {
char gateway[INET_ADDRSTRLEN];
inet_ntop(AF_INET, RTA_DATA(rta), gateway, INET_ADDRSTRLEN);
printf("Gateway: %s\n", gateway);
}
}
}
if (nlh->nlmsg_type == NLMSG_DONE)
break;
}
close(netlink_fd);
return 0;
}
```
运行程序后,它会输出路由表中的网关地址。请注意,需要以root权限运行该程序。
阅读全文