直接在内核态接收外部的网络报文,打印器目的地址和源地址,在用户态我可以使用socket API,进行网络的收发,在内核态不能使用socket API我该在哪里找我的报文,报文收发是通过socket_buf ,这个我知道但是具体怎么打开这个socket_buf取报文呢?
在Linux内核中,你可以使用Netfilter框架来实现截取并打印网络报文的目的地址和源地址。Netfilter框架提供了一组API,可以在内核态对网络报文进行操作,包括截取、修改、转发等。
以下是一个简单的示例,展示如何在内核态截取网络报文并打印目的地址和源地址:
1.编写一个内核模块(Kernel Module),使用Netfilter框架的API来实现截取网络报文的功能。
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>
#include <stdio.h>
static struct nf_hook_ops nfho;
static unsigned int hook_func(const struct sk_buff *skb,
const struct nf_hook_state *state)
{
struct iphdr *ip_header;
__be16 frag_off;
unsigned int offset;
ip_header = (struct iphdr *)skb_network_header(skb);
frag_off = ip_header->frag_off;
offset = ntohs(frag_off) & IP_OFFSET;
if (offset == 0) { // 如果是第一个IP数据包片
char *data = skb->data;
struct iphdr *ip;
__be16 sport, dport;
ip = (struct iphdr *)data;
sport = ip->source;
dport = ip->dest;
printf("Source Port: %d\n", ntohs(sport));
printf("Destination Port: %d\n", ntohs(dport));
printf("Source IP: %pI4\n", &ip->saddr);
printf("Destination IP: %pI4\n", &ip->daddr);
}
return NF_ACCEPT;
}
static struct nf_hook_ops nfho = {
.hook = hook_func,
.pf = PF_INET,
.hooknum = NF_INET_PRE_ROUTING,
.priority = NF_IP_PRI_FIRST,
};
void init(void)
{
nf_register_hook(&nfho);
}
void exit(void)
{
nf_unregister_hook(&nfho);
}
2.编译并加载内核模块。使用以下命令编译:
$ make -C /lib/modules/$(uname -r)/build M=$(pwd) modules
然后使用以下命令加载模块:
$ sudo insmod netfilter.ko
3.在内核日志中查看打印的目的地址和源地址。你可以使用dmesg命令来查看内核日志:
$ dmesg | tail -n 10
在输出中,你将看到类似以下的内容,其中包含了目的地址和源地址:
[ 0.000000] Source Port: 23456
[ 0.000000] Destination Port: 80
[ 0.000000] Source IP: 192.168.0.100
[ 0.000000] Destination IP: 192.168.0.101
请注意,这只是一个简单的示例,仅用于说明如何在内核态截取网络报文并打印目的地址和源地址。