[英]Casting with raw packet data and inet_ntoa()
試圖為數據包嗅探器編寫處理程序。 我遇到了關於cast和inet_ntoa()
。 代碼如下:
uint32_t *iphdr_srcaddr = malloc(sizeof(uint32_t));
if (*packet_ethertype == ETHERTYPE_IP) { /* IPv4 */
// copy packet data to vars
memcpy(iphdr_srcaddr, packet+26, 4);
// change to host-byte-order
*iphdr_srcaddr = ntohl(*iphdr_srcaddr);
struct in_addr *test;
test = (struct in_addr*) iphdr_srcaddr;
printf("uint32_t: %u\n", *iphdr_srcaddr); // Gives the correct long integer for the address
printf("struct in_addr: %u\n", test->s_addr); // Gives the correct long integer through the cast
char *test2;
test2 = inet_ntoa(*test);
}
現在,如果我嘗試printf("%s\\n", test)
我會得到SEGV。 我敢肯定我正在混淆指針,價值觀和做某種愚蠢的演員。 運行期間收到錯誤:
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff787ec61 in __strlen_sse2 () from /lib/libc.so.6
編譯警告,我確信這指向了正確的方向,但我不確定它意味着什么以及如何解決它:
mypcap.c: In function ‘handle_sniffed’:
mypcap.c:61:15: warning: assignment makes pointer from integer without a cast [enabled by default]
這指的是行test2 = inet_ntoa(*test);
警告可能表示您在inet_ntoa()
范圍內沒有正確的原型(因為您沒有包含正確的標頭)。 這意味着編譯器假定它的返回類型為int
。
當你應該通過test2
時,你也將test
傳遞給printf()
。
此外:
malloc()
來分配單個uint32_t
; ntohl()
因為inet_ntoa()
期望它以網絡字節順序輸入; 和 inet_ntoa()
已過期 - 應在新代碼中使用inet_ntop()
。 嘗試:
#include <arpa/inet.h>
if (*packet_ethertype == ETHERTYPE_IP) { /* IPv4 */
struct in_addr sin_addr;
char straddr[INET_ADDRSTRLEN];
memcpy(&sin_addr.s_addr, packet+26, 4);
if (inet_ntop(AF_INET, &sin_addr, straddr, sizeof straddr))
printf("%s\n", straddr);
else
perror("inet_ntop");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.