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

前端 未结 2 1483
星月不相逢
星月不相逢 2020-12-30 07:55

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

In my netfilter hook function, I have:

         


        
相关标签:
2条回答
  • 2020-12-30 08:06

    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.

    0 讨论(0)
  • 2020-12-30 08:07

    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);
    
    0 讨论(0)
提交回复
热议问题