在使用pcap时,我声明了rtp结构,当我试图指向数据包的这个区域时,我发现根据我的声明,它以一种不同的方式工作。
我写了这个:
struct udphdr *udp;
struct rtphdr *rtp, *rtp2;
udp = (struct udphdr*) (packet + sizeof(struct ether_header) + (ip->ip_hl*4));
rtp = (struct rtphdr*) (packet + sizeof(struct ether_header) + (ip->ip_hl*4) + sizeof(struct udphdr));
rtp2 = (struct rtphdr*) (udp + sizeof(struct udphdr));
printf("UPD header: %p\n",udp);
printf("RTP header 1: %p\n",rtp);
printf("RTP header 2: %p\n",rtp2);产出如下:
UDP报头: 0x7fcea3802222 RTP报头1: 0x7fcea380222a RTP头2: 0x7fcea 3802262
为什么第一个声明会添加UDP头的8字节(0x2a - 0x22 = 0x8),而另一个则会添加更多。
谢谢
发布于 2013-10-29 18:12:47
指针算法在C(以及C++和Objective和Objective++)中的工作方式是,假定指针指向数组的第N个元素,如果将K添加到指针,则结果指向同一个数组的N+Kth元素。
这意味着,在字节可寻址机器上(您的机器是字节可寻址的,考虑到非字节可寻址机器运行的C编译器不支持libpcap),如果您有指向一个M字节长的对象的指针,如果将K添加到该指针中,则与该添加结果对应的地址将是M*K字节超过该指针中的地址。
因此,除非您有指向1字节值的指针,否则向指针添加sizeof值并不是您想要做的。
这意味着
rtp2 = (struct rtphdr*) (udp + sizeof(struct udphdr)); 是错的。如果udp指向一个UDP头,并且您想要指向超过UDP头的位置,则需要执行以下任何一种操作
rtp2 = (struct rtphdr*) (udp + 1); 或
rtp2 = (struct rtphdr*) ((char *)udp + sizeof(struct udphdr)); 我假设pointer是指向char或unsigned char的指针,就像传递给libpcap回调的指针一样,所以您使用pointer所做的算法是正确的。
https://stackoverflow.com/questions/19665090
复制相似问题