libpromeki 1.0.0-alpha
PROfessional MEdia toolKIt
 
Loading...
Searching...
No Matches
ipv6address.h
Go to the documentation of this file.
1
8#pragma once
9
10
11#include <promeki/config.h>
12#if PROMEKI_ENABLE_CORE
13#include <cstdint>
14#include <cstring>
15#include <promeki/namespace.h>
16#include <promeki/string.h>
17#include <promeki/result.h>
18#include <promeki/array.h>
19#include <promeki/platform.h>
20#include <promeki/list.h>
21
22#if defined(PROMEKI_PLATFORM_WINDOWS)
23#include <winsock2.h>
24#include <ws2tcpip.h>
25#elif !defined(PROMEKI_PLATFORM_EMSCRIPTEN)
26#include <netinet/in.h>
27#endif
28
29PROMEKI_NAMESPACE_BEGIN
30
31class Ipv4Address;
32class Ipv6Address;
33class MacAddress;
34class TextStream;
35
59class Ipv6Address {
60 public:
62 using DataFormat = Array<uint8_t, 16>;
63
65 using List = ::promeki::List<Ipv6Address>;
66
78 static Result<Ipv6Address> fromString(const String &str);
79
81 static Ipv6Address any() { return Ipv6Address(); }
82
84 static Ipv6Address loopback();
85
87 Ipv6Address() : _addr{}, _scopeId(0) {}
88
93 explicit Ipv6Address(const DataFormat &bytes) : _addr(bytes), _scopeId(0) {}
94
99 explicit Ipv6Address(const uint8_t *bytes) : _scopeId(0) {
100 for (size_t i = 0; i < 16; ++i) _addr[i] = bytes[i];
101 }
102
104 bool isNull() const { return _addr.isZero() && _scopeId == 0; }
105
107 bool isLoopback() const;
108
110 bool isMulticast() const { return _addr[0] == 0xFF; }
111
113 bool isLinkLocal() const { return _addr[0] == 0xFE && (_addr[1] & 0xC0) == 0x80; }
114
116 bool isV4Mapped() const;
117
119 bool isSiteLocal() const { return _addr[0] == 0xFE && (_addr[1] & 0xC0) == 0xC0; }
120
125 uint32_t scopeId() const { return _scopeId; }
126
131 void setScopeId(uint32_t id) { _scopeId = id; }
132
137 const DataFormat &data() const { return _addr; }
138
143 const uint8_t *raw() const { return _addr.data(); }
144
152 String toString() const;
153
161 Ipv4Address toIpv4() const;
162
172 MacAddress multicastMac() const;
173
174#if !defined(PROMEKI_PLATFORM_EMSCRIPTEN)
181 static Result<Ipv6Address> fromSockAddr(const struct sockaddr_in6 *sa);
182
193 Error toSockAddr(struct sockaddr_in6 *sa) const;
194#endif
195
197 bool operator==(const Ipv6Address &other) const {
198 return _addr == other._addr && _scopeId == other._scopeId;
199 }
201 bool operator!=(const Ipv6Address &other) const { return !(*this == other); }
203 bool operator<(const Ipv6Address &other) const {
204 int cmp = std::memcmp(_addr.data(), other._addr.data(), 16);
205 if (cmp != 0) return cmp < 0;
206 return _scopeId < other._scopeId;
207 }
208
209 private:
210 DataFormat _addr;
211 uint32_t _scopeId;
212};
213
215TextStream &operator<<(TextStream &stream, const Ipv6Address &addr);
216
217PROMEKI_NAMESPACE_END
218
219PROMEKI_FORMAT_VIA_TOSTRING(promeki::Ipv6Address);
220
221#endif // PROMEKI_ENABLE_CORE