我正在编写一个注册netfilter钩子的内核模块。我正在尝试使用sk_buff->saddr成员获取呼叫者的ip地址。有没有办法获得人类可读的IP,即x.x格式?
我找到了函数inet_ntop(),但它似乎在内核头文件中不可用。如何将\xC0\xA8\x00\x01转换为192.168.0.1?
发布于 2009-04-02 15:28:27
include/linux/kernel.h中定义了两个宏
ipv4地址的NIP6和ipv6地址的NIPQUAD。
#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地址。例如:
printk(KERN_DEBUG "Received packet from source address: %d.%d.%d.%d!\n",NIPQUAD(iph->saddr));希望这能有所帮助。
发布于 2012-11-16 19:52:56
您应该使用printk()提供的%pI4扩展格式说明符:
printk(KERN_DEBUG "IP addres = %pI4\n", &local_ip);发布于 2015-06-13 00:23:24
printk可以直接处理这个问题:
IPv4地址:
%pI4 1.2.3.4
%pi4 001.002.003.004
%p[Ii]4[hnbl]
For printing IPv4 dot-separated decimal addresses. The 'I4' and 'i4'
specifiers result in a printed address with ('i4') or without ('I4')
leading zeros.
The additional 'h', 'n', 'b', and 'l' specifiers are used to specify
host, network, big or little endian order addresses respectively. Where
no specifier is provided the default network/big endian order is used.
Passed by reference.IPv6地址:
%pI6 0001:0002:0003:0004:0005:0006:0007:0008
%pi6 00010002000300040005000600070008
%pI6c 1:2:3:4:5:6:7:8
For printing IPv6 network-order 16-bit hex addresses. The 'I6' and 'i6'
specifiers result in a printed address with ('I6') or without ('i6')
colon-separators. Leading zeros are always used.
The additional 'c' specifier can be used with the 'I' specifier to
print a compressed IPv6 address as described by
http://tools.ietf.org/html/rfc5952
Passed by reference.参考:https://www.kernel.org/doc/Documentation/printk-formats.txt
https://stackoverflow.com/questions/584713
复制相似问题