【问题标题】:How to print correctly a IP using NETFILTER in C如何在 C 中使用 NETFILTER 正确打印 IP
【发布时间】:2022-01-08 13:00:00
【问题描述】:

我有以下代码,它只捕获数据包并打印 IP 源和目标:

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>
#include <linux/ip.h>

static struct nf_hook_ops nfho;

unsigned int hook_func(void *priv, struct sk_buff *skb, const struct nf_hook_state *state) {
    struct iphdr *ip_header = (struct iphdr *)skb_network_header(skb);
    unsigned int src_ip = (unsigned int)ip_header->saddr;
    unsigned int dest_ip = (unsigned int)ip_header->daddr;
    printk(KERN_INFO "IPs: %u \t to \t %u \n", src_ip, dest_ip);
    return NF_ACCEPT;   
}

int init_module() { /* Fill in our hook structure */
    nfho.hook = hook_func; /* Handler function */
    nfho.hooknum = NF_INET_PRE_ROUTING; /* First hook for IPv4 */
    nfho.pf = PF_INET;
    nfho.priority = NF_IP_PRI_FIRST; /* Make our function first */
    nf_register_hook(&nfho);
    return 0;
}

void cleanup_module() {
    nf_unregister_hook(&nfho);
}

但是,我不知道如何正确打印它(如 IP X.X.X.X),因为它显示以下信息:

IP:16777343 到 16842879

IP:4198316624 到 67108884

IP:16842879 到 16777343

有人可以帮助我吗? 谢谢!

【问题讨论】:

标签: c linux-kernel ip netfilter


【解决方案1】:

我想你可以通过 inet_ntoa 函数来获取可读的 IP 地址:https://linux.die.net/man/3/inet_ntoa

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
  • 这是一个关于内核空间的问题,请参阅 [linux-kernel] 标签、特定于 linux 的 #includes、printk(KERN_INFO 等。因此,您的答案与链接一样是错误的- to 文档用于用户空间。
【解决方案2】:

使用%pI4 作为格式说明符。

例如printk(KERN_DEBUG "IPs: %pI4 \t to \t %pI4 \n", &amp;src_ip, &amp;dest_ip);

这记录在 Documentation/printk-formats.txt 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多