2016-05-22 52 views
0

我试图监控我的ARP表在linux中使用C++,迄今为止唯一的解决方案是轮询/ proc/net/arp的每个时间间隔,并与以前的状态进行比较。监控ARP表的变化

我可以使用netlink套接字来接收来自内核的事件吗?

我环顾四周,找不到一个直接的答案,我发现像ip-monitor这样的收费,但没有找到他们如何获得这些数据。

如果netlink套接字无法提供此信息,是否有任何其他方式来提取事件,而不是轮询?

+0

我也可以用类似inotify的东西来管理变化事件,然后比较当前状态与以前的但inotify无法监视/ proc –

+0

我已经找到[this](http://stackoverflow.com/questions/11788326/extract-current-route-from-netlink-message-code-attached)来监控路由表的变化,我可以使用相同的技术来监控ARP表吗? –

回答

2

我能找到怎样用网络连接套接字上的ARP表改变的事件,我已经错过了唯一的事情是如何从事件中提取ARP细节,但现在这是不行的:

int sock; 
static struct sockaddr_nl g_addr; 

/* Zeroing addr */ 
bzero(&g_addr, sizeof(g_addr)); 
g_addr.nl_family = AF_NETLINK; 
g_addr.nl_groups = nl_mgrp(RTNLGRP_NEIGH); 

if ((sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE)) < 0) { 
    printf("socket() error: %s", strerror(errno)); 
    return -1; 
} 

if (bind(sock, (struct sockaddr *) &g_addr, sizeof(g_addr)) < 0) { 
    printf("bind() error: %s", strerror(errno)); 
    return -1; 
} 

char buffer[4096]; 
int received_bytes = 0; 

while (true) { 
    received_bytes = recv(sock, buffer, sizeof(buffer), 0); 
    if (received_bytes > 0) { 
     printf("Event\n"); 
     // How to parse the event 
    } 
}