-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathipv6_address.cc
86 lines (68 loc) · 2.19 KB
/
ipv6_address.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Copyright 2023 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net-base/ipv6_address.h"
#include <algorithm>
#include <arpa/inet.h>
#include <base/check.h>
namespace net_base {
// static
std::optional<IPv6Address> IPv6Address::CreateFromString(
std::string_view address_string) {
DataType data;
if (inet_pton_string_view(AF_INET6, address_string, data.data()) <= 0) {
return std::nullopt;
}
return IPv6Address(data);
}
// static
std::optional<IPv6Address> IPv6Address::CreateFromBytes(
base::span<const char> bytes) {
return CreateFromBytes(base::span<const uint8_t>(
reinterpret_cast<const uint8_t*>(bytes.data()), bytes.size()));
}
// static
std::optional<IPv6Address> IPv6Address::CreateFromBytes(
base::span<const uint8_t> bytes) {
return CreateAddressFromBytes<IPv6Address>(bytes);
}
IPv6Address::IPv6Address(const struct in6_addr& addr) {
std::copy_n(reinterpret_cast<const uint8_t*>(&addr), kAddressLength,
data_.begin());
}
bool IPv6Address::IsZero() const {
return std::all_of(data_.begin(), data_.end(),
[](uint8_t byte) { return byte == 0; });
}
bool IPv6Address::operator==(const IPv6Address& rhs) const {
return data_ == rhs.data_;
}
bool IPv6Address::operator!=(const IPv6Address& rhs) const {
return !(*this == rhs);
}
bool IPv6Address::operator<(const IPv6Address& rhs) const {
return data_ < rhs.data_;
}
std::vector<uint8_t> IPv6Address::ToBytes() const {
return {std::begin(data_), std::end(data_)};
}
std::string IPv6Address::ToByteString() const {
return {reinterpret_cast<const char*>(data_.data()), kAddressLength};
}
struct in6_addr IPv6Address::ToIn6Addr() const {
struct in6_addr ret;
memcpy(&ret, data_.data(), kAddressLength);
return ret;
}
std::string IPv6Address::ToString() const {
char address_buf[INET6_ADDRSTRLEN];
const char* res =
inet_ntop(AF_INET6, data_.data(), address_buf, sizeof(address_buf));
DCHECK(res);
return std::string(address_buf);
}
std::ostream& operator<<(std::ostream& os, const IPv6Address& address) {
os << address.ToString();
return os;
}
} // namespace net_base