Question

Working with pcap I declare the rtp struct and when I try to point to this area of the packet I found that depending on my declaration, it works in a different way.

I wrote this:

struct udphdr *udp;
struct rtphdr *rtp, *rtp2;
udp = (struct udphdr*) (packet + sizeof(struct ether_header) + (ip->ip_hl*4));
rtp = (struct rtphdr*) (packet + sizeof(struct ether_header) + (ip->ip_hl*4) + sizeof(struct udphdr));
rtp2 = (struct rtphdr*) (udp + sizeof(struct udphdr));    
printf("UPD header: %p\n",udp);
printf("RTP header 1: %p\n",rtp);
printf("RTP header 2: %p\n",rtp2);

And the output is:

UDP header: 0x7fcea3802222

RTP header 1: 0x7fcea380222a

RTP header 2: 0x7fcea3802262

Why with the first declaration it adds the 8 Bytes of the UDP header (0x2a - 0x22 = 0x8) and with the other it a lot more.

Thanks

Was it helpful?

Solution

The way pointer arithmetic works in C (and C++ and Objective-C and Objective-C++) is that the pointer is presumed to point to the Nth element of an array, and if you add K to the pointer, the result points to the N+Kth element of the same array.

This means that, on a byte-addressible machine (your machine is byte-addressible, given that the OSes run by non-byte-addressible machines with C compilers don't support libpcap), if you have a pointer to an object that's M bytes long, if you add K to that pointer, the address corresponding to the result of that addition will be M*K bytes past the address in that pointer.

So, unless you have a pointer to a 1-byte value, adding a sizeof value to the pointer is not what you want to do.

This means that

rtp2 = (struct rtphdr*) (udp + sizeof(struct udphdr));    

is wrong. If udp points to a UDP header, and you want to point past the UDP header, you need to do either

rtp2 = (struct rtphdr*) (udp + 1);    

or

rtp2 = (struct rtphdr*) ((char *)udp + sizeof(struct udphdr));    

I presume pointer is a pointer to char or unsigned char, as would be handed to a libpcap callback, so the arithmetic you're doing with pointer is correct.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top