srdusr
aboutsummaryrefslogtreecommitdiffstats
path: root/include/wireframe/net/ipv4.hpp
blob: f53b4f2632ab0f0489017d2c0aa4bad8544b1b75 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#pragma once

#include <algorithm>
#include <array>
#include <cstdint>
#include <optional>
#include <span>

#include "wireframe/byteio.hpp"

namespace wireframe::net {

inline constexpr std::uint8_t kProtoIcmp = 1;
inline constexpr std::uint8_t kProtoTcp = 6;
inline constexpr std::uint8_t kProtoUdp = 17;

struct Ipv4Address {
    std::array<unsigned char, 4> bytes;
};

struct Ipv4Header {
    std::uint8_t version;
    std::uint8_t ihl;  // header length in 32-bit words
    std::uint16_t total_length;
    std::uint8_t ttl;
    std::uint8_t protocol;
    Ipv4Address src;
    Ipv4Address dst;
};

struct Ipv4Packet {
    Ipv4Header header;
    std::span<const unsigned char> payload;
};

inline std::optional<Ipv4Packet> parse_ipv4(std::span<const unsigned char> bytes) {
    if (bytes.size() < 20) return std::nullopt;

    std::uint8_t version = static_cast<std::uint8_t>(bytes[0] >> 4);
    std::uint8_t ihl = bytes[0] & 0x0F;
    std::size_t header_len = static_cast<std::size_t>(ihl) * 4;
    if (version != 4 || header_len < 20 || bytes.size() < header_len) return std::nullopt;

    Ipv4Header header{};
    header.version = version;
    header.ihl = ihl;
    header.total_length = read_be16(bytes, 2);
    header.ttl = bytes[8];
    header.protocol = bytes[9];
    std::copy_n(bytes.begin() + 12, 4, header.src.bytes.begin());
    std::copy_n(bytes.begin() + 16, 4, header.dst.bytes.begin());

    return Ipv4Packet{header, bytes.subspan(header_len)};
}

}  // namespace wireframe::net