0

So I'm reading the post here And I've come across this block of code

char packet[sizeof(icmphdr)];
memset(packet, 0, sizeof(packet));

icmphdr *pkt = (icmphdr *)packet;

From what I understand, the are declaring a char array that is the size of icmphdr and then it gets fuzzy for me after that. The line following this I don't even know where to start to interprete this.

Community
  • 1
  • 1
Wusiji
  • 599
  • 1
  • 7
  • 24
  • 2
    the datatype `packet` is a buffer to save packets. and `pkt` is a pointer to the beginning of packet. `memset` is used to clear the contents of the buffer. – Alexander Oh Jul 08 '14 at 07:51
  • @Alex Wrong frame! This is an answer, not a comment. – TobiMcNamobi Jul 08 '14 at 07:56
  • @OP The code in the referenced post is quite hard to read and IMHO anything but 'clean'. – TobiMcNamobi Jul 08 '14 at 07:58
  • In this snippet (and the code linked therein) it is somewhat pointless. The casting and buffer management gets considerably more interesting further down in the `while(1)` loop. A simple `icmphdr packet = {0}, *pkt = &packet;` would have sufficed for this specific code block. I concur with Tobi. That code is anything-but-exemplary. – WhozCraig Jul 08 '14 at 07:58

1 Answers1

1

Look at the type definition for icmphdr. Effectively you're convincing the compiler that your char (byte) array is actually a icmphdr (I'm guessing) struct. This means that you can read raw bytes into the array and then access the different parts of that array as though they're a struct.

So lets say that icmphdr is defined as:

typedef struct
{
    int sequence_number;
    int data_size;
    bool fragment;
} icmphdr;

That means that you then do:

read(socket_fd, packet, sizeof(icmphdr));

And then you can do things like:

int sequence= packet->sequence_number;

Of course if you do this, you have to be REALLY careful about struct packing.

Joe
  • 7,378
  • 4
  • 37
  • 54
  • And [that's undefined behavior anyway](http://stackoverflow.com/questions/24598335/is-the-strict-aliasing-rule-really-a-two-way-street). I don't understand why the author of this code didn't declare the packet as a `icmphdr` originally, and only casting its address to a `char *` when needed. – The Paramagnetic Croissant Jul 08 '14 at 08:30
  • Agreed, but I'm guessing what I wrote is what they were doing - correct or not! – Joe Jul 08 '14 at 08:37