I am a newbie in C progrmming and I have looked at the following code:
struct iphdr *iph = (struct iphdr *)Buffer;
What does the expression mean?
here is the link to the code http://www.binarytides.com/packet-sniffer-code-c-linux/
It casts buffer
to a pointer to struct iphdr
and then initializes iph
to that pointer. This is used because buffer
is a pointer to a buffer of raw bytes, but in this function it is known that the bytes stored in the buffer follow the format of a struct iphdr
. Hence the struct iphdr
can be used to access the contents of the buffer, rather than having to interpret and manipulate the raw bytes.
edit: To clarify (as per comments): The cast does not copy or convert anything. It is basically just telling the compiler “I know that buffer
is supposed to contain unsigned char
s but at this particular time those bytes are actually a struct iphdr
so let me access them through the pointer iph
in a more convenient way”.