简体   繁体   中英

Casting with raw packet data and inet_ntoa()

Trying to write a handler for a packet sniffer. I'm having issues with casting and inet_ntoa() . Code is as follows:

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);
}

Now if I try to printf("%s\\n", test) I get SEGV. I'm sure I'm mixing up pointers, values and doing some sort of stupid casting. Error received during run below:

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff787ec61 in __strlen_sse2 () from /lib/libc.so.6

Compilation warning as well, I'm sure this is pointing me in the correct direction, but I'm not sure what to it means and how I can fix it:

mypcap.c: In function ‘handle_sniffed’:
mypcap.c:61:15: warning: assignment makes pointer from integer without a cast [enabled by default]

This refers to the line test2 = inet_ntoa(*test);

The warning probably indicates that you don't have a correct prototype in scope for inet_ntoa() (because you haven't included the right header). This means that the compiler assumes it has a return type of int .

You're also passing test to printf() when you should be passing test2 .

In addition:

  • There's no need to use malloc() to allocate a single uint32_t ;
  • You don't need to call ntohl() because inet_ntoa() expects its input in network byte order; and
  • inet_ntoa() is out of date - inet_ntop() should be used in new code.

Try:

#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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM