I have the following code, it only catch the packets and prints the IP source and destination:
#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);
}
But, I don't know how to print it correctly (like a IP X.X.X.X) because it shows the following information:
IPs: 16777343 to 16842879
IPs: 4198316624 to 67108884
IPs: 16842879 to 16777343
Can someone help me? Thanks!
CodePudding user response:
Use %pI4
for the format specifier. This is documented in Documentation/printk-formats.txt.
CodePudding user response:
I think you can you inet_ntoa function to get the readable IP address: https://linux.die.net/man/3/inet_ntoa