简体   繁体   English

如何编写内核模块以在内核中查找路由表和 arp 缓存?

[英]How to write a kernel module to lookup route table and arp cache in kernel?

我想写一个模块在内核中查找路由表以获取网关ip,并使用ip查找arp缓存以获取网关的mac地址。

Not sure why you need a kernel module for this.不知道为什么你需要一个内核模块。 Everything you need to find the default gw mac address is available in user space...用户空间中提供了查找默认 gw mac 地址所需的一切...

#!/usr/bin/env python

import re
import socket
from struct import pack

hex_gateway = re.findall('\t00000000\t([0-9A-F]*)\t', open('/proc/net/route').read())[0]
if not hex_gateway: sys.exit(1)

gw_ip = socket.inet_ntoa(pack('I', int(hex_gateway, 16)))

gw_mac = False
for line in open('/proc/net/arp').readlines():
    if line.startswith(gw_ip):
        gw_mac = line.split()[3]
        break

if gw_mac:print gw_mac
else:sys.exit(1)

fib_lookup : looking up route table. fib_lookup : 查找路由表。 Defined at net/ipv4/route.c .定义在net/ipv4/route.c

ipv4_neigh_lookup : using struct neighbour (ARP protocol is implemented by neighbour subsystem) to send the SKB. ipv4_neigh_lookup : 使用struct neighbor(ARP协议由neighbor子系统实现)发送SKB。

Go through ip_route_input_slow for more detail about the route table and neighbour subsystem.有关路由表和邻居子系统的更多详细信息,请访问ip_route_input_slow

I think you want to get the mac address of default gateway.After researching bit,I got an answer.我想你想得到默认网关的mac地址。经过研究,我得到了答案。 ip_route_output - can be used to check routes __ipv4_neigh_lookup - can be used to arp lookup ip_route_output - 可用于检查路由__ipv4_neigh_lookup - 可用于 arp 查找

Example code:示例代码:

    struct rtable *rt;
    struct neighbour *n;
    struct net_device *eth0;
    struct net *ndev;
    unsigned int paddr = 134744072;    //destination ip ex: 8.8.8.8
    unsigned int haddr;
    eth0 = dev_get_by_name(&init_net,"eth0"); //network interface name
    ndev=dev_net(eth0);
    rt = ip_route_output(ndev,paddr,0,RT_TOS(0),eth0->ifindex);
    haddr=rt->rt_gateway;                     //default gateway ip
    printk(KERN_INFO "[G] Default Gateway IP [%d.%d.%d.%d] ",(haddr>>0)&0xff,(haddr>>8)&0xff,(haddr>>16)&0xff,(haddr>>24)&0xff);
    n = __ipv4_neigh_lookup(eth0,rt->rt_gateway);
    printk(KERN_INFO "[G] Default Gateway mac [%pM] ",n->ha); // default gateway mac

There are other ways to get default gateway mac.They are based on fib_lookup().还有其他获取默认网关mac的方法。它们基于fib_lookup()。 But, they are a little bit long .ip_route_output also call fib_lookup().但是,它们有点长 .ip_route_output 也调用 fib_lookup()。

ip_route_output() -> ip_route_output_key() ->ip_route_output_flow() ->__ip_route_output_key() -> fib_lookup()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM