使用C++将UDP数据包存储在Structure中

Store UDP packet in Structure using C++

本文关键字:Structure 存储 数据包 C++ UDP 使用      更新时间:2023-10-16

我是C++编程的新手。我正在尝试创建一个与Camera通信的软件。我能够将Camera与我的Software进行通信。通过WireShark,我可以看到相机正在向我发送packet,即hex representation

我想把这些数据包存储在结构中。

例如:-

我收到的包裹是

char packet_bytes[] = {
0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x01, 0x10, 
};

每个值都是1 byte我想把确切的值存储在这个struct

存储在Struct中的我的代码

m_receivedBytes = recvfrom(sock, (char*)m_packetBuffer, sizeof(m_packetBuffer), 0, (sockaddr*)&cameraInfo, &m_socketLength);
if (m_receivedBytes > 0)
{
switch (m_protocolType)
{
case StreamProtocol: ProtocolStruct.m_status = m_packetBuffer[0] + m_packetBuffer[1];
ProtocolStruct.m_blockID = m_packetBuffer[2] + m_packetBuffer[3];
ProtocolStruct.m_format = m_packetBuffer[4];
ProtocolStruct.m_packetID = m_packetBuffer[5] + m_packetBuffer[6] + m_packetBuffer[7];
switch (ProtocolStruct.m_format)
{
case 1: ProtocolStruct.m_leader->m_fieldInfo = m_packetBuffer[9];
ProtocolStruct.m_leader->m_payloadType = m_packetBuffer[10] + m_packetBuffer[11];
break;
default:
break;
}
break;
default:        
break;
}

数据包大小是22,所以我这样存储值,我知道这是错误的。

示例

如果2个字节是10 01,那么当我使用+运算符时,结果是11,这是不正确的。正确的答案应该是1001

所以有人能告诉我如何将所有数据放入Structure 中吗

在处理电信数据包时,必须确保两个对等端之间共享完全相同的字节布局和顺序。问题是结构定义是编译器特有的;一种快速而肮脏的方法是使用"打包"布局:

struct __attribute__((__packed__)) ProtocolStruct
{
__int16         m_status;
__int16         m_blockID;
__int8          m_format;
__int32         m_packetID;
struct Trailer *m_trailer;
}ProtocolStruct;

这解决了布局问题,但不解决字节顺序问题。

然而,这并不总是足够的参见Is gcc';s __attribute__((已打包((/#pragma pack不安全?