userver: userver/utils/macaddr.hpp Source File
Loading...
Searching...
No Matches
macaddr.hpp
1#pragma once
2
3/// @file userver/utils/macaddr/macaddr_base.hpp
4/// @brief MAC address types
5
6#include <array>
7#include <stdexcept>
8#include <string>
9#include <utility>
10
11#include <userver/utils/encoding/hex.hpp>
12
13USERVER_NAMESPACE_BEGIN
14
15namespace utils {
16
17/// @ingroup userver_containers
18///
19/// @brief Base class for Macaddr/Macaddr8
20template <std::size_t N>
21class MacaddrBase final {
22 static_assert(N == 6 || N == 8, "Address can only be 6 or 8 bytes size");
23
24 public:
25 using OctetsType = std::array<unsigned char, N>;
26
27 MacaddrBase() = default;
28
29 explicit MacaddrBase(const OctetsType& macaddr) noexcept
30 : macaddr_(macaddr) {}
31
32 /// @brief Get octets of MAC-address
33 const OctetsType& GetOctets() const noexcept { return macaddr_; }
34
35 friend bool operator==(const MacaddrBase<N>& a,
36 const MacaddrBase<N>& b) noexcept {
37 return a.GetOctets() == b.GetOctets();
38 }
39
40 friend bool operator!=(const MacaddrBase<N>& a,
41 const MacaddrBase<N>& b) noexcept {
42 return !(a == b);
43 }
44
45 private:
46 OctetsType macaddr_ = {0};
47};
48
49/// @ingroup userver_containers
50///
51/// @brief 48-bit MAC address
52using Macaddr = MacaddrBase<6>;
53
54/// @ingroup userver_containers
55///
56/// @brief 64-bit MAC address
57using Macaddr8 = MacaddrBase<8>;
58
59/// @brief Get 48-bit MAC address as a string in "xx:xx:.." format.
60std::string MacaddrToString(Macaddr macaddr);
61
62/// @brief Get 64-bit MAC address as a string in "xx:xx:.." format.
63std::string Macaddr8ToString(Macaddr8 macaddr);
64
65/// @brief Get 48-bit MAC address from std::string.
66Macaddr MacaddrFromString(const std::string& str);
67
68/// @brief Get 64-bit MAC address from std::string.
69Macaddr8 Macaddr8FromString(const std::string& str);
70
71} // namespace utils
72
73USERVER_NAMESPACE_END