Search code examples
pointersstruct

Struct and Pointers: Please help me understand this line of code


Please help me understand what does the last line does:

int PCKT_LEN = 8192;

char buffer[PCKT_LEN];
  struct iphdr *ip = (struct iphdr *) buffer;
  struct udphdr *udp = (struct udphdr *) (buffer + sizeof(struct iphdr));

I know this one , I kind of understand like:

(struct udphdr *)  -> Means cast to a udphdr "object"/instance or something like that.

This one, I have doubt / don't understand:

(buffer + sizeof(struct iphdr)) 
        
        This one, I don't quite understand. Is it because it uses the ADDRESS being returned by buffer and then adds the actual size of the buffer until the last byte as an offset before starting to allocate udp memory range?  I guess the it wants to start the address of udp right after the ip ?

If I do the last line like below, will it be the same ? (I changed buffer to ip)

   struct udphdr *udp = (struct udphdr *) (ip + sizeof(struct iphdr));

Thank you.

Regards,

X

( I am a newbie on CPP and just started on pointers and structs.)


Solution

  • It simply says that there is a memory buffer buffer which contains an iphdr structure (*ip), directly followed by a udphdr structure (*udp).

    The second line sets the udp pointer to exactly one byte after the end of the ip structure in memory. (it takes the base pointer and then advances it by the amount of bytes an iphdr structure needs in memory)

    Note there is absolutely no allocation involved other than the buffer memory. The code simply "overlays" the flat array buffer with memory structures that comprise a udp packet. That is normally done to be able to pick bytes from well-defined offsets of a flat buffer. (it is much more meaningful to access udp->flags than *(buffer + offset) )