使用C++将UDP数据包存储在Structure中
Store UDP packet in Structure using C++
我是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不安全?
相关文章:
- 将字符串存储在c++中的稳定内存中
- std::原子加载和存储都需要吗
- C++:将控制台输出存储在宏中更好吗
- 使用QProcess执行命令,并将结果存储在QStringList中
- 访问存储在向量C++中的结构的多态成员
- 如何从存储在std::映射中的std::集中删除元素
- 存储模板类型以强制转换回派生<T>
- 类型总是使用其大小存储在内存中吗
- 当字符串存储在变量中时,如何将字符串转换为wchar_t
- 使用无符号字符数组有效存储内存
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 使用 pqxx 将 std::vector 存储在 postgresql 中,并从数据库中检索它
- 带结构的二维矢量:如何存储元素
- 添加存储在向量中的大整数的函数出现问题
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 在std::vector上存储带有模板的类实例
- 谷歌测试中的期望值存储在哪里
- 为什么C中的通用链表中存储的数据已损坏
- 在c++中获取两个大int,并将它们存储在数组中
- 使用C++将UDP数据包存储在Structure中