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