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

这一生的挚爱 提交于 2019-12-03 12:29:39

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/9296835/convert-source-ip-address-from-struct-iphdr-to-string-equivalent-using-linux-ne

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!