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