12

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

In my netfilter hook function, I have:

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.

Jake
  • 16,329
  • 50
  • 126
  • 202
  • @ott-- The conversion has to be done in the kernel module. I could not find a header file in linux/ folder containing inet_ntoa() function. I did find in_aton() in linux/inet.h which does exactly the opposite, converts char* to __be32. – Jake Feb 15 '12 at 16:24
  • Oops, kernel. Try this; `printk("ip-address is " NIPQUAD_FMT "\n", NIPQUAD(ip_header->saddr));`. I cannot access my linux hosts from here, so I can't tell where the macros are defined. And it's for ipv4 only. – ott-- Feb 15 '12 at 17:02

2 Answers2

25

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

So with IPv4, you could use something like:

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.

fnl
  • 2,209
  • 19
  • 17
1

Try in4_pton() function in net/core/utils.c (definition: 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, '\0', NULL);
Xinyi Li
  • 852
  • 8
  • 9