我怎么能得到IP和端口从有效载荷无符号字符,但

How can i get IP and PORT from payload unsigned char buf?

本文关键字:有效 无符号 字符 怎么能 IP      更新时间:2023-10-16

我有unsigned char buf:

IP位于位置197,端口位于位置205。我如何从这个无符号字符中得到正确的IP和端口?

我尝试了一些数字转换,但没有运气:(

我假设,IP从第197个位置开始,它在数组中占据4个位置(每个八分区1个),1个位置用于端口。在C/c++中,第197个位置应该以索引196访问。因此,您可以通过以下方式访问IP和端口地址的4个八分位数,

short int octants[] ={buf[196],buf[197],buf[198],buf[199]} ;
short int portId = buf[204] ; 

好吧,我找到了解决方案,谢谢你在正确的方向踢家伙:)

输出正确结果的代码:

printf("IP: %d.%d.%d.%d", buf[197], buf[198], buf[199], buf[200]);
int port = 0;                           // Start with zero
port |= buf[204] & 0xFF;                // Assign first byte to port using bitwise or.
port <<= 8;                             // Shift the bits left by 8 (so the byte from before is on the correct position)
port |= buf[205] & 0xFF;
printf(" Port: %d", port);

结果为:IP: 8.8.8.8 Port: 53