How do I correctly traverse through packets after reading the header and finding out the packetlength?

62 Views Asked by At

Given this header format:

Header Format

I am trying to traverse and print the Length and Num Market Updates:

std::ifstream fileOpener(m_rawInputFileName, std::ios::binary);
if (!fileOpener.is_open())
{
    std::cout << "Error: could not open file" << std::endl;
    fileOpener.close();
    return;
}

short int packetLength;
short int numOfMarketUpdates;
while (fileOpener.read((char *)&packetLength, 2) &&
        fileOpener.read((char *)&numOfMarketUpdates, 2))
{
    cout << packetLength << ":" << numOfMarketUpdates << endl;
    fileOpener.seekg(-4, std::ios::cur);
    fileOpener.seekg(packetLength, std::ios::cur);
}

What am I doing wrong, or is the data inaccurate?

1

There are 1 best solutions below

0
User010000100110100101110010 On

Answer: I missed an Important Detail: "All data is in network byte order." Hence, the correct code was:

#include <arpa/inet.h>

std::ifstream fileOpener(m_rawInputFileName, std::ios::binary);
if (!fileOpener.is_open())
{
    std::cout << "Error: could not open file" << std::endl;
    return;
}

short int packetLength;
short int numOfMarketUpdates;
while (fileOpener.read((char *)&packetLength, 2) &&
        fileOpener.read((char *)&numOfMarketUpdates, 2))
{
    packetLength = nthos(packetLength);
    numOfMarketUpdates = nthos(numOfMarketUpdates);
    cout << packetLength << ":" << numOfMarketUpdates << endl;
    fileOpener.seekg(-4, std::ios::cur);
    fileOpener.seekg(packetLength, std::ios::cur);
}

nthos converts network byte order to host byte order. Network Byte order is configured to be in a big-endian which may be different than your host byte order so It would not make sense unless you convert it into your host byte order.

Credits to user253751 for pointing this out.