Reputation: 163
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/
Upvotes: 0
Views: 722
Reputation: 27854
buffer
is a pointer to a unsigned char
array that is being used to storage the raw packet data.
This is recasting the type of buffer
to be unsderstood as a pointer to struct iphdr
, so you can assign it to iph
and read it as a structure. Technically this is just supressing the compiler error that would say that the value of buffer
cannot be assigned to iph
because they are of different types, despite the fact they are both pointers.
Alternatively, you can make buffer
of type void*
instead.
A pointer to void
can be assigned to any other pointer type without need to recast it's type:
void* buffer = malloc(65536);
...
void ProcessPacket(void* buffer, int size) {
struct iphdr *iph = buffer;
...
}
Upvotes: 0
Reputation: 42129
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”.
Upvotes: 2