我可以帮您进行翻译。这段文本是关于编程的内容,询问如何通过netlink套接字来监控路由变化,并获取更新后的路由地址。
代码如下:
代码如下:
#include <sys/socket.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#define ERR_RET(x) do { perror(x); return EXIT_FAILURE; } while (0);
void loop (int sock)
{
struct sockaddr_nl nladdr;
struct msghdr msg;
struct iovec iov[2];
struct nlmsghdr nlh;
char buffer[65536];
iov[0].iov_base = (void *)&nlh;
iov[0].iov_len = sizeof(nlh);
iov[1].iov_base = (void *)buffer;
iov[1].iov_len = sizeof(buffer);
msg.msg_name = (void *)&(nladdr);
msg.msg_namelen = sizeof(nladdr);
msg.msg_iov = iov;
msg.msg_iovlen = sizeof(iov)/sizeof(struct iovec);
if ( recvmsg (sock, &msg, 0) )
{
if ( nlh.nlmsg_type == RTM_NEWROUTE )
{
printf ("New route message\n");
}
else if ( nlh.nlmsg_type == RTM_DELROUTE )
{
printf ("Del route message\n");
}
}
}
int main(int argc, char *argv[])
{
int sock = -1;
struct sockaddr_nl addr;
bzero (&addr, sizeof(addr));
if ( (sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE) ) < 0 )
ERR_RET("socket");
addr.nl_family = AF_NETLINK;
addr.nl_groups = RTMGRP_IPV4_ROUTE;
if (bind(sock,(struct sockaddr *)&addr,sizeof(addr))<0)
ERR_RET("bind");
while (1)
loop (sock);
return 0;
}