srdusr
aboutsummaryrefslogtreecommitdiffstats
path: root/include/wireframe/net/udp.hpp
blob: 07664c2655b4383d00def656d6303d8e0402336e (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
#pragma once

#include <cstdint>
#include <optional>
#include <span>

#include "wireframe/byteio.hpp"

namespace wireframe::net {

inline constexpr std::size_t kUdpHeaderLen = 8;

struct UdpHeader {
    std::uint16_t src_port;
    std::uint16_t dst_port;
    std::uint16_t length;
};

struct UdpDatagram {
    UdpHeader header;
    std::span<const unsigned char> payload;
};

inline std::optional<UdpDatagram> parse_udp(std::span<const unsigned char> bytes) {
    if (bytes.size() < kUdpHeaderLen) return std::nullopt;

    UdpHeader header{};
    header.src_port = read_be16(bytes, 0);
    header.dst_port = read_be16(bytes, 2);
    header.length = read_be16(bytes, 4);

    return UdpDatagram{header, bytes.subspan(kUdpHeaderLen)};
}

}  // namespace wireframe::net