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
24public:
25 using OctetsType = std::array<unsigned char, N>;
26
27 MacaddrBase() = default;
28
29 explicit MacaddrBase(const OctetsType& macaddr) noexcept : macaddr_(macaddr) {}
30
31 /// @brief Get octets of MAC-address
32 const OctetsType& GetOctets() const noexcept { return macaddr_; }
33
34 friend bool operator==(const MacaddrBase<N>& a, const MacaddrBase<N>& b) noexcept {
35 return a.GetOctets() == b.GetOctets();
36 }
37
38 friend bool operator!=(const MacaddrBase<N>& a, const MacaddrBase<N>& b) noexcept { return !(a == b); }
39
40private:
41 OctetsType macaddr_ = {0};
42};
43
44/// @ingroup userver_containers
45///
46/// @brief 48-bit MAC address
47using Macaddr = MacaddrBase<6>;
48
49/// @ingroup userver_containers
50///
51/// @brief 64-bit MAC address
52using Macaddr8 = MacaddrBase<8>;
53
54/// @brief Get 48-bit MAC address as a string in "xx:xx:.." format.
55std::string MacaddrToString(Macaddr macaddr);
56
57/// @brief Get 64-bit MAC address as a string in "xx:xx:.." format.
58std::string Macaddr8ToString(Macaddr8 macaddr);
59
60/// @brief Get 48-bit MAC address from std::string.
61Macaddr MacaddrFromString(const std::string& str);
62
63/// @brief Get 64-bit MAC address from std::string.
64Macaddr8 Macaddr8FromString(const std::string& str);
65
66} // namespace utils
67
68USERVER_NAMESPACE_END