Why cast where it does not seem to need
Only with one excerpt can not explain much. But it is unlikely to be just aesthetic. Even because I have not seen where it looks most beautiful. cast unnecessary is usually done by those who do not know how to program.
Cast does not do a conversion at all, only tells the compiler that the programmer is aware that the operation involves the use of information that may be originally different but which he wants to use as a definite type.
Some compilers may not complain, but it is safer to issue at least one warning that the operation is potentially misleading. Obliging to be explicit is a way to avoid bugs . Luckily today compilers often require casting to ensure that this is the intention.
What this code does
This code is reading a TCP / IP packet that is nothing more than a huge bytes sequence with some meaning only for the protocol. Aware of the protocol, the programmer understands the blocks of this huge sequence that indicate certain information contained within the protocol.
What this code is doing is picking up each of these blocks and assigning it to a variable each.
How does he do this?
It takes the address of the packet containing the first information, IP. Then it throws a pointer at the variable ip
of the code that will point to the first block of the package, that is where the package IP is located.
Since this pointer has no meaning for the code, it may not be what you should do. So the compiler requires you to put cast to tell you that you want this "arbitrary" pointer to be considered a pointer to the iphdr
The same can be said for cast following for the variable icmp
. There you are making a shifting of the address initially obtained to map to another structure (note that the offset is exactly the size of the first information). That is, it will point to the second block of information contained in the package. The cast serves to indicate to the compiler that this value pointed to in this sequence can be read quietly as a "pointer to a icmphdr
structure."
It would not necessarily have to be creating several isolated variables for each block of protocol information. It could throw this information into a structure designed specifically to receive protocol information. In some scenarios this is the most correct thing to do. In this case the cast on each item would not even be needed. The layout of a TCP / IP package is practically a struct
ready. Of course if you are going to do some conversions you can not take advantage of the whole package to map directly to the structure. But if you need data conversion, the package can not be used for pointing.