sk_buff的IP地址 [英] IP-address from sk_buff
问题描述
我正在编写一个注册了netfilter钩子的内核模块.我正在尝试通过使用sk_buff->saddr
成员来获取呼叫者的IP地址.有什么方法可以获取人类可读的IP,即x.x.x.x格式?
I am writing a kernel module which registers a netfilter hook. I am trying to get the ip address of the caller by using the sk_buff->saddr
member. Is there a way I can get the IP in human readable i.e. x.x.x.x format?
我找到了函数inet_ntop()
,但是它似乎在内核头文件中不可用.如何将\ xC0 \ xA8 \ x00 \ x01转换为192.168.0.1?
I found the function inet_ntop()
but it doesn't seem to be available in kernel headers. How do I convert \xC0\xA8\x00\x01 to 192.168.0.1 ?
推荐答案
在include/linux/kernel.h中定义了两个宏
There are two macros defined in include/linux/kernel.h
对于IPV4地址为NIPQUAD,对于IPV6地址为NIP6.
NIPQUAD for ipv4 addresses and NIP6 for ipv6 addresses.
#define NIPQUAD(addr) \
((unsigned char *)&addr)[0], \
((unsigned char *)&addr)[1], \
((unsigned char *)&addr)[2], \
((unsigned char *)&addr)[3]
#define NIP6(addr) \
ntohs((addr).s6_addr16[0]), \
ntohs((addr).s6_addr16[1]), \
ntohs((addr).s6_addr16[2]), \
ntohs((addr).s6_addr16[3]), \
ntohs((addr).s6_addr16[4]), \
ntohs((addr).s6_addr16[5]), \
ntohs((addr).s6_addr16[6]), \
ntohs((addr).s6_addr16[7])
内核源代码中有很多示例,利用这些示例以人类可读的格式打印ip地址.例如:
There are ample examples in the kernel sources that make use of these to print ip addresses in human-readable format. For instance:
printk(KERN_DEBUG "Received packet from source address: %d.%d.%d.%d!\n",NIPQUAD(iph->saddr));
希望这会有所帮助.
这篇关于sk_buff的IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!