简体   繁体   中英

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...

#!/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. Defined at net/ipv4/route.c .

ipv4_neigh_lookup : using struct neighbour (ARP protocol is implemented by neighbour subsystem) to send the SKB.

Go through ip_route_input_slow for more detail about the route table and neighbour subsystem.

I think you want to get the mac address of default gateway.After researching bit,I got an answer. ip_route_output - can be used to check routes __ipv4_neigh_lookup - can be used to arp lookup

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(). But, they are a little bit long .ip_route_output also call fib_lookup().

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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