简体   繁体   English

在 c++ 中解析数据包数据的最佳方法是什么?

[英]What's the best way to parse a packet data in c++?

I'm transcoding a Delphi App to C++ and got a problem to get the correct way to do the cases of packet headers in C++.我正在将 Delphi 应用程序转码为 C++ 并遇到问题,无法正确处理 C++ 中的数据包标头的情况。

The Headers Comes as "Dword" in a UCHAR buf and i dont want make like: if (packet[0] == 0xFF && packet[1] == 0xFF...);标头在 UCHAR buf 中以“Dword”的形式出现,我不想像这样:if (packet[0] == 0xFF && packet[1] == 0xFF...);

Ex: Delphi Working with switch case:例如:Delphi 使用开关盒:

              case PDword(@Packet[6])^ of
                $68FB0200:
                  begin
                     //Dword match correctly
                  End;
              end;

is there a way to do the same in C++ like the Delphi Example?有没有办法像 Delphi 示例一样在 C++ 中做同样的事情?

Already checked for some methds but ever fails the comparsion.已经检查了一些方法,但比较失败。

UCHAR               *Packet ;
Packet = ParsePacket(buf->Buf, buf->Size);
// The ParsePacket Returns FB 00 00 00 78 00 01 F3 02 FD

DWORD Op1 = 0x01F302FD;
DWORD *p_dw = (DWORD*) Packet[6];
if (p_dw == Op1)
{
 //Dword never match...
}

Yes, the portable C (and C++) way is:是的,便携式 C(和 C++)方式是:

DWORD const Op1 = 0x01F302FD;
if (0 == memcmp(Packet + 6, &Op1, sizeof Op1)) { ... }

Note that we haven't tried to access the bytes at Packet+6 as a 32-bit quantity... they're likely to be misaligned for that.请注意,我们没有尝试将Packet+6处的字节作为 32 位数量来访问……它们可能会因此而错位。 We're just asking whether the same sequence of 4 bytes exists there as exist in Op1 .我们只是询问那里是否存在与Op1中相同的 4 字节序列。

The obvious issue with DWORD *p_dw = (DWORD*) Packet[6] is that you take a value as an address. DWORD *p_dw = (DWORD*) Packet[6]的明显问题是您将值作为地址。 You probably meant DWORD *p_dw = (DWORD*)&(Packet[6]) .您可能的意思是DWORD *p_dw = (DWORD*)&(Packet[6])

Note, however, that you get additional troubles for two reasons:但是请注意,由于两个原因,您会遇到额外的麻烦:

First, alignment could be wrong such that the pointer received is not a valid address to be taken for dereferencing a DWORD.首先,alignment 可能是错误的,因此接收到的指针不是用于取消引用 DWORD 的有效地址。 This is undefined behaviour then.这是未定义的行为。

Second, you depend on a specific endianess.其次,您依赖于特定的字节序。

To overcome the first issue, you could use memcpy :要克服第一个问题,您可以使用memcpy

DWORD Op2 = 0;
memcpy(&Op2,Packet+6,sizeof(Op2));

To overcome both the first and the second issue, you'll need to sum the bytes on your own, eg:为了克服第一个和第二个问题,您需要自己对字节求和,例如:

DWORD Op2 = Packet[6]<<24 | Packet[7]<<16 | Packet[8]<<8 | Packet[9]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM