【发布时间】:2020-02-22 15:50:52
【问题描述】:
我有以下工作函数,它接收一个准备好 ICMP 响应的套接字并将其读入缓冲区,但我很难理解代码的流程,并希望有人纠正/确认我的理解。我的理解如下:
- 定义了一个名为“buffer”的 1024 字符数组指针用作缓冲区。
- 创建了两个名为“ip”和“icmp”的指针以指向 iphdr 和 icmphdr 结构。
- “ip”指针设置为指向“缓冲区”指针,该指针现在已转换为 iphdr 结构指针
- “icmp”指针设置为指向“缓冲区”指针 + struct iphdr 的大小,该大小现在转换为 icmphdr struct 指针
这是我不太明白的第四点。 'icmp' 指针地址是否堆叠在 'ip' 指针地址下方,而 '(buff + sizeof(struct iphdr))' 是否引用了 'icmp' 指针应指向的内存点?有没有什么地方可以读到关于使用这种类型的偏移的类型转换? `
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 ] ]以上代码是标准 C++ 中的未定义行为;编译器扩展可能没问题。我不知道C的合法性 -
@RichardCritten 我想是
[ [ iphdr ] [ icmphdr ] ],不是吗?
标签: c++ c sockets pointers casting