0

In order to write a packet sniffer I need to be able to index through the bytes of the packet.

I have come from python, in python you can index through a list very easily eg;

variable = data[2:5]. In c++ you can't do it like that.

Here is a snippet of my code

void ethernet_frame(char raw_data[19]){

    struct ethernet{ 
        char dest_mac[6] = get_mac_addr(raw_data[:7]);
        char src_mac[6] = get_mac_addr(raw_data[7:14]);
        unsigned short proto  = proto[14:17]; 
    };
}

I expect that there is an alternative or perhaps a library I can use to index through the packet.

3

2 Answers 2

2

There's no built-in way of doing this, but C++ allows you to create abstractions to achieve your goals. E.g.

void ethernet_frame(std::array<char, 19> raw_data)
{
    struct ethernet
    {
        std::array<char, 6> dest_mac;
        std::array<char, 6> src_mac;
    };

    ethernet e{slice<0, 7>(raw_data), slice<7, 14>(raw_data)};
}

Where slice is something along the lines of:

template <std::size_t Begin, std::size_t End, typename T>
auto slice(const T& range)
{
    constexpr auto count = End - Begin - 1;
    std::array<std::decay_t<decltype(*range.begin())>, count> result;
    std::copy(range.begin() + Begin, range.begin() + End, result.begin());
    return result;
}
Sign up to request clarification or add additional context in comments.

Comments

0

C++ is not Python. So you cannot code like this.

You might want to use pointer arithmetic (e.g. raw_data+7 if raw_data is some char*)

You could use iterators and range for. Then you want to use containers like std::array or std::vector

Please take several days or weeks to read a good C++ programming book. We don't have time or space for that here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.