2012-03-07 58 views
0

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

+2

为什么你需要一个模块?你不能使用iptables? – 2012-03-07 06:45:52

+2

你的问题是什么?和[你有什么尝试](http://mattgemmell.com/2008/12/08/what-have-you-tried/)? – 2012-03-07 07:08:30

+0

我想编写一个程序并将它编译为.ko,而我使用insmod来加载这个模块时,它会激活网关的地址。所以我应该在内核中查找路由表,但我不知道该怎么做。 – gotounix 2012-03-07 12:11:19

回答

1

不知道你为什么需要一个内核模块。你需要找到默认网关的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) 
1

fib_lookup:查找路由表。定义在net/ipv4/route.c

ipv4_neigh_lookup:使用struct neighbor(ARP协议由邻居子系统实现)发送SKB。

有关路由表和邻居子系统的更多详细信息,请参阅ip_route_input_slow