I have the following working function that takes in a socket ready for an ICMP response and reads it into a buffer but I am struggling to understand the flow of the code and wanted someone to correct/confirm my understanding. My understanding is as follows:
- A 1024 character array pointer called 'buffer' is defined to be used as the buffer.
- Two pointers called 'ip' and 'icmp' are created to point to iphdr and icmphdr stucts.
- The 'ip' pointer is set to point to the 'buffer' pointer which is now converted to an iphdr struct pointer
- The 'icmp' pointer is set to point to the 'buffer' pointer + the size of struct iphdr which is now converted to an icmphdr struct pointer
It is the 4th point that I dont quite understand. Is the 'icmp' pointer address stacked underneath the 'ip' pointer address and '(buff + sizeof(struct iphdr))' is referencing the point in memory the 'icmp' pointer should point to? Is there anywhere I can read about type casting using this type of offsetting? `
int read_icmp_answer(int *sock){
char buff[1024];
struct iphdr *ip;
struct icmphdr *icmp;
ip = (struct iphdr *)buff;
icmp = (struct icmphdr *) (buff + sizeof(struct iphdr));
if(read(*sock, buff, sizeof(buff)) > 0) {
if(icmp->type == 0 && icmp->code == 0) return 1;
else return -1;
}
return 0;
}
`
[ iphdr [ icmphdr ] ]The above code is Undefined Behaviour in Standard C++; might be OK with compiler extensions. I don't know about the legality inC- Richard Critten[ [ iphdr ] [ icmphdr ] ], isn't it? - Lightness Races in Orbit