libxr  1.0
Want to be the best embedded framework
Loading...
Searching...
No Matches
net.hpp
1#pragma once
2
3#include <cstdint>
4#include <cstring>
5#include <cstdio>
6#include "libxr_mem.hpp"
7
8namespace LibXR
9{
10
11constexpr size_t IPADDR_STRLEN = 16; // "255.255.255.255" + '\0'
12constexpr size_t MACADDR_STRLEN = 18; // "FF:FF:FF:FF:FF:FF" + '\0'
13
18{
19 uint8_t bytes[4]{};
20
21 static IPAddressRaw FromString(const char* str)
22 {
23 IPAddressRaw ip{};
24 std::sscanf(str, "%hhu.%hhu.%hhu.%hhu",
25 &ip.bytes[0], &ip.bytes[1], &ip.bytes[2], &ip.bytes[3]);
26 return ip;
27 }
28
29 void ToString(char out[IPADDR_STRLEN]) const
30 {
31 std::snprintf(out, IPADDR_STRLEN, "%u.%u.%u.%u",
32 bytes[0], bytes[1], bytes[2], bytes[3]);
33 }
34
35 bool operator==(const IPAddressRaw& other) const
36 {
37 return Memory::FastCmp(bytes, other.bytes, 4) == 0;
38 }
39
40 bool operator!=(const IPAddressRaw& other) const
41 {
42 return !(*this == other);
43 }
44};
45
50{
51 char str[IPADDR_STRLEN]{};
52
53 static IPAddressStr FromRaw(const IPAddressRaw& raw)
54 {
55 IPAddressStr s{};
56 raw.ToString(s.str);
57 return s;
58 }
59
60 IPAddressRaw ToRaw() const
61 {
62 return IPAddressRaw::FromString(str);
63 }
64};
65
70{
71 uint8_t bytes[6]{};
72
73 static MACAddressRaw FromString(const char* str)
74 {
75 MACAddressRaw mac{};
76 std::sscanf(str, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx",
77 &mac.bytes[0], &mac.bytes[1], &mac.bytes[2],
78 &mac.bytes[3], &mac.bytes[4], &mac.bytes[5]);
79 return mac;
80 }
81
82 void ToString(char out[MACADDR_STRLEN]) const
83 {
84 std::snprintf(out, MACADDR_STRLEN, "%02X:%02X:%02X:%02X:%02X:%02X",
85 bytes[0], bytes[1], bytes[2],
86 bytes[3], bytes[4], bytes[5]);
87 }
88
89 bool operator==(const MACAddressRaw& other) const
90 {
91 return Memory::FastCmp(bytes, other.bytes, 6) == 0;
92 }
93
94 bool operator!=(const MACAddressRaw& other) const
95 {
96 return !(*this == other);
97 }
98};
99
104{
105 char str[MACADDR_STRLEN]{};
106
107 static MACAddressStr FromRaw(const MACAddressRaw& raw)
108 {
109 MACAddressStr s{};
110 raw.ToString(s.str);
111 return s;
112 }
113
114 MACAddressRaw ToRaw() const
115 {
116 return MACAddressRaw::FromString(str);
117 }
118};
119
124{
125 public:
126 virtual ~NetworkInterface() = default;
127
128 virtual bool Enable() = 0;
129 virtual void Disable() = 0;
130 virtual bool IsConnected() const = 0;
131
132 virtual IPAddressRaw GetIPAddress() const = 0;
133 virtual MACAddressRaw GetMACAddress() const = 0;
134};
135
136} // namespace LibXR
static int FastCmp(const void *a, const void *b, size_t size)
快速内存比较 / Fast memory comparison
抽象网络接口类 / Abstract base for network interfaces
Definition net.hpp:124
LibXR 命名空间
原始 IPv4 地址 / Raw IPv4 address
Definition net.hpp:18
字符串形式 IPv4 地址 / IPv4 address as string
Definition net.hpp:50
原始 MAC 地址 / Raw MAC address
Definition net.hpp:70
字符串形式 MAC 地址 / MAC address as string
Definition net.hpp:104