2012-02-15 166 views
8

我想將來自使用netfilter捕獲的數據包的源IP地址&轉換爲char *。將來自struct iphdr *的源IP地址轉換爲使用Linux netfilter的字符串等效

在我的netfilter鉤子函數,我有:

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 

感謝。

+0

With inet_ntoa()? – 2012-02-15 16:10:33

+0

@ ott--轉換必須在內核模塊中完成。我無法在包含inet_ntoa()函數的linux /文件夾中找到頭文件。我在linux/inet.h中找到了in_aton(),它完全相反,它將char *轉換爲__be32。 – Jake 2012-02-15 16:24:59

+0

糟糕,內核。嘗試這個; 'printk(「ip-address是」NIPQUAD_FMT「\ n」,NIPQUAD(ip_header-> saddr));'。我無法從這裏訪問我的Linux主機,所以我無法確定宏定義的位置。它僅適用於ipv4。 – 2012-02-15 17:02:05

回答

13

內核的printf()函數族具有IP地址的特殊格式說明符(用於IPv4地址的%pI4,用於IPv6的%pI6)。因此,與IPv4的

,你可以使用類似:

char source[16]; 
snprintf(source, 16, "%pI4", &ip_header->saddr); // Mind the &! 

或寫信到動態分配的內存。

如果您只是想打印調試輸出,您還可以使用printk()。對於%p的許多其他功能,請參閱this document

相關問題