Lucky
Lucky

Reputation: 49

Store UDP packet in Structure using C++

I am new in C++ programming. I am trying to create a Software which communicates to Camera. I am able to communicate Camera to my Software. Through WireShark I can see that camera is sending me packet which is hex representation.

I want to store that packets in structure.

For Example:-

The packet I get is

 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, 
};

each value is of 1 byte I want to store the exact value in this struct

My Code to store in 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;
            }

The packet size is 22 so I store the value like this, I know this is wrong.

Example

If the 2 bytes are 10 01 the when I use + operator then result is 11 which is incorrect The correct answer should be 1001.

So can anyone please tell me how to put all that data in Structure

Upvotes: 1

Views: 670

Answers (1)

tomrtc
tomrtc

Reputation: 555

When dealing with telecoms packets, you have to insure that the same exact byte layout and order is shared between the two peers. You problem is that a struct definition is compiler specific ; one quick and dirty way is to use a "packed" layout :

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

}ProtocolStruct;

This solve the layout problem but not the byte order problem also name endianess.

However not always enough see Is gcc's __attribute__((packed)) / #pragma pack unsafe?

Upvotes: 1

Related Questions