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 <cstdio>
5#include <cstring>
6
7#include "libxr_mem.hpp"
8
9namespace LibXR
10{
11
12constexpr size_t IPADDR_STRLEN = 16; // "255.255.255.255" + '\0'
13constexpr size_t MACADDR_STRLEN = 18; // "FF:FF:FF:FF:FF:FF" + '\0'
14
19{
20 uint8_t bytes[4]{};
21
22 static IPAddressRaw FromString(const char* str)
23 {
24 IPAddressRaw ip{};
25 std::sscanf(str, "%hhu.%hhu.%hhu.%hhu", &ip.bytes[0], &ip.bytes[1], &ip.bytes[2],
26 &ip.bytes[3]);
27 return ip;
28 }
29
30 void ToString(char out[IPADDR_STRLEN]) const
31 {
32 std::snprintf(out, IPADDR_STRLEN, "%u.%u.%u.%u", bytes[0], bytes[1], bytes[2],
33 bytes[3]);
34 }
35
36 bool operator==(const IPAddressRaw& other) const
37 {
38 return Memory::FastCmp(bytes, other.bytes, 4) == 0;
39 }
40
41 bool operator!=(const IPAddressRaw& other) const { return !(*this == other); }
42};
43
48{
49 char str[IPADDR_STRLEN]{};
50
51 static IPAddressStr FromRaw(const IPAddressRaw& raw)
52 {
53 IPAddressStr s{};
54 raw.ToString(s.str);
55 return s;
56 }
57
58 IPAddressRaw ToRaw() const { return IPAddressRaw::FromString(str); }
59};
60
65{
66 uint8_t bytes[6]{};
67
68 static MACAddressRaw FromString(const char* str)
69 {
70 MACAddressRaw mac{};
71 std::sscanf(str, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", &mac.bytes[0], &mac.bytes[1],
72 &mac.bytes[2], &mac.bytes[3], &mac.bytes[4], &mac.bytes[5]);
73 return mac;
74 }
75
76 void ToString(char out[MACADDR_STRLEN]) const
77 {
78 std::snprintf(out, MACADDR_STRLEN, "%02X:%02X:%02X:%02X:%02X:%02X", bytes[0],
79 bytes[1], bytes[2], bytes[3], bytes[4], bytes[5]);
80 }
81
82 bool operator==(const MACAddressRaw& other) const
83 {
84 return Memory::FastCmp(bytes, other.bytes, 6) == 0;
85 }
86
87 bool operator!=(const MACAddressRaw& other) const { return !(*this == other); }
88};
89
94{
95 char str[MACADDR_STRLEN]{};
96
97 static MACAddressStr FromRaw(const MACAddressRaw& raw)
98 {
99 MACAddressStr s{};
100 raw.ToString(s.str);
101 return s;
102 }
103
104 MACAddressRaw ToRaw() const { return MACAddressRaw::FromString(str); }
105};
106
111{
112 public:
113 virtual ~NetworkInterface() = default;
114
115 virtual bool Enable() = 0;
116 virtual void Disable() = 0;
117 virtual bool IsConnected() const = 0;
118
119 virtual IPAddressRaw GetIPAddress() const = 0;
120 virtual MACAddressRaw GetMACAddress() const = 0;
121};
122
123} // 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:111
LibXR 命名空间
Definition ch32_can.hpp:14
原始 IPv4 地址 / Raw IPv4 address
Definition net.hpp:19
字符串形式 IPv4 地址 / IPv4 address as string
Definition net.hpp:48
原始 MAC 地址 / Raw MAC address
Definition net.hpp:65
字符串形式 MAC 地址 / MAC address as string
Definition net.hpp:94