【问题标题】:Store UDP packet in Structure using C++使用 C++ 在结构中存储 UDP 数据包
【发布时间】:2019-01-12 02:18:29
【问题描述】:

我是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

我的代码存储在结构中

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所以我这样存储值,我知道这是错误的。

示例

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

那么谁能告诉我如何将所有这些数据放入结构中

【问题讨论】:

  • 先生,如果我使用 (|, &, >) 那么我可以得到 (1001) 吗?
  • 加法是正确的——10 + 1 = 11,不管你的数字基数是多少——但加法不是你要找的。了解按位运算和移位(|&>><<)。
  • 您通常可以通过向左移位 (<<) 和按位或运算 (|) 重新组装事物 - 例如x = (buf[n] << 24) | (buf[n+1] << 16) | (buf[n+2] << 8) | buf[n+3] - 但您需要确保 m_packetBufferunsigned char / uint8_t 的数组。或者,您可以瞄准例如uint32_t* p = reinterpret_cast<uint32_t*>(&m_packetBuffer[n]) 然后读取 *p(在这种情况下,将 m_packetBuffer 保留为 char 的数组)。无论哪种方式,您都可能需要转换为 endianness - 请参阅 htonl 等。

标签: c++ sockets udp structure packet


【解决方案1】:

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

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__((packed)) / #pragma pack unsafe?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2020-08-01
    • 2019-07-03
    • 2017-09-27
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多