使用 Linux netfilter 将源 IP 地址从 struct iphdr* 转换为等效字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9296835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:35:53  来源:igfitidea点击:

Convert source IP address from struct iphdr* to string equivalent using Linux netfilter

clinuxkernelkernel-modulenetfilter

提问by Jake

I want to convert the source & destination IP addresses from a packet captured using netfilter to char *.

我想将使用 netfilter 捕获的数据包中的源和目标 IP 地址转换为 char *。

In my netfilter hook function, I have:

在我的 netfilter 钩子函数中,我有:

sock_buff = skb; // argument 2 of hook function

// ip_header is struct iphdr*
ip_header = (struct iphdr *)skb_network_header(sock_buff);

// now how to convert ip_header->saddr & ip_header->daddr to char *
// ip_header->saddr & ip_header->daddr are of type __be32

Thanks.

谢谢。

采纳答案by fnl

The kernel's family of printf()functions has a special format specifier for IP-addresses (%pI4for IPv4-addresses, %pI6for IPv6).

内核的printf()函数族有一个特殊的 IP 地址格式说明符(%pI4对于 IPv4 地址,%pI6对于 IPv6)。

So with IPv4, you could use something like:

因此,对于 IPv4,您可以使用以下内容:

char source[16];
snprintf(source, 16, "%pI4", &ip_header->saddr); // Mind the &!

Or write to dynamically allocated memory.

或者写入动态分配的内存。

If you simply want to print debug-output, you can also use printk(). For the many other features of %p, see this document.

如果您只想打印调试输出,也可以使用printk(). 有关 的许多其他功能%p,请参阅此文档

回答by Xinyi Li

Try in4_pton()function in net/core/utils.c(definition: https://elixir.bootlin.com/linux/latest/source/net/core/utils.c#L118)

尝试in4_pton()函数net/core/utils.c(定义:https: //elixir.bootlin.com/linux/latest/source/net/core/utils.c#L118

#include <linux/inet.h>

char source[16];
in4_pton(source, -1, &ip_header->saddr, '##代码##', NULL);