簡體   English   中英

使用原始數據包數據和inet_ntoa()進行轉換

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM