2 * Copyright 2017 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include <folly/IPAddress.h>
24 #include <folly/Format.h>
25 #include <folly/String.h>
26 #include <folly/detail/IPAddressSource.h>
35 size_t hash_value(const IPAddress& addr) {
38 ostream& operator<<(ostream& os, const IPAddress& addr) {
42 void toAppend(IPAddress addr, string* result) {
43 result->append(addr.str());
45 void toAppend(IPAddress addr, fbstring* result) {
46 result->append(addr.str());
49 bool IPAddress::validate(StringPiece ip) noexcept {
50 return IPAddressV4::validate(ip) || IPAddressV6::validate(ip);
54 IPAddressV4 IPAddress::createIPv4(const IPAddress& addr) {
58 return addr.asV6().createIPv4();
63 IPAddressV6 IPAddress::createIPv6(const IPAddress& addr) {
67 return addr.asV4().createIPv6();
72 CIDRNetwork IPAddress::createNetwork(
73 StringPiece ipSlashCidr,
74 int defaultCidr, /* = -1 */
75 bool applyMask /* = true */) {
76 if (defaultCidr > std::numeric_limits<uint8_t>::max()) {
77 throw std::range_error("defaultCidr must be <= UINT8_MAX");
80 split("/", ipSlashCidr, vec);
81 vector<string>::size_type elemCount = vec.size();
83 if (elemCount == 0 || // weird invalid string
84 elemCount > 2) { // invalid string (IP/CIDR/extras)
85 throw IPAddressFormatException(sformat(
86 "Invalid ipSlashCidr specified. Expected IP/CIDR format, got '{}'",
89 IPAddress subnet(vec.at(0));
91 uint8_t((defaultCidr > -1) ? defaultCidr : (subnet.isV4() ? 32 : 128));
95 cidr = to<uint8_t>(vec.at(1));
97 throw IPAddressFormatException(
98 sformat("Mask value '{}' not a valid mask", vec.at(1)));
101 if (cidr > subnet.bitCount()) {
102 throw IPAddressFormatException(sformat(
103 "CIDR value '{}' is > network bit count '{}'",
107 return std::make_pair(applyMask ? subnet.mask(cidr) : subnet, cidr);
111 std::string IPAddress::networkToString(const CIDRNetwork& network) {
112 return sformat("{}/{}", network.first.str(), network.second);
116 IPAddress IPAddress::fromBinary(ByteRange bytes) {
117 if (bytes.size() == 4) {
118 return IPAddress(IPAddressV4::fromBinary(bytes));
119 } else if (bytes.size() == 16) {
120 return IPAddress(IPAddressV6::fromBinary(bytes));
122 string hexval = detail::Bytes::toHex(bytes.data(), bytes.size());
123 throw IPAddressFormatException(
124 sformat("Invalid address with hex value '{}'", hexval));
128 Expected<IPAddress, IPAddressFormatError> IPAddress::tryFromBinary(
129 ByteRange bytes) noexcept {
130 // Check IPv6 first since it's our main protocol.
131 if (bytes.size() == 16) {
132 return IPAddressV6::tryFromBinary(bytes);
133 } else if (bytes.size() == 4) {
134 return IPAddressV4::tryFromBinary(bytes);
136 return makeUnexpected(IPAddressFormatError::UNSUPPORTED_ADDR_FAMILY);
141 IPAddress IPAddress::fromLong(uint32_t src) {
142 return IPAddress(IPAddressV4::fromLong(src));
144 IPAddress IPAddress::fromLongHBO(uint32_t src) {
145 return IPAddress(IPAddressV4::fromLongHBO(src));
148 // default constructor
149 IPAddress::IPAddress() : addr_(), family_(AF_UNSPEC) {}
151 // public string constructor
152 IPAddress::IPAddress(StringPiece str) : addr_(), family_(AF_UNSPEC) {
153 auto maybeIp = tryFromString(str);
154 if (maybeIp.hasError()) {
155 throw IPAddressFormatException(
156 to<std::string>("Invalid IP address '", str, "'"));
158 *this = std::move(maybeIp.value());
161 Expected<IPAddress, IPAddressFormatError> IPAddress::tryFromString(
162 StringPiece str) noexcept {
163 // need to check for V4 address second, since IPv4-mapped IPv6 addresses may
165 if (str.find(':') != string::npos) {
166 return IPAddressV6::tryFromString(str);
167 } else if (str.find('.') != string::npos) {
168 return IPAddressV4::tryFromString(str);
170 return makeUnexpected(IPAddressFormatError::UNSUPPORTED_ADDR_FAMILY);
174 // public sockaddr constructor
175 IPAddress::IPAddress(const sockaddr* addr) : addr_(), family_(AF_UNSPEC) {
176 if (addr == nullptr) {
177 throw IPAddressFormatException("sockaddr == nullptr");
179 family_ = addr->sa_family;
180 switch (addr->sa_family) {
182 const sockaddr_in* v4addr = reinterpret_cast<const sockaddr_in*>(addr);
183 addr_.ipV4Addr = IPAddressV4(v4addr->sin_addr);
187 const sockaddr_in6* v6addr = reinterpret_cast<const sockaddr_in6*>(addr);
188 addr_.ipV6Addr = IPAddressV6(*v6addr);
192 throw InvalidAddressFamilyException(addr->sa_family);
196 // public ipv4 constructor
197 IPAddress::IPAddress(const IPAddressV4 ipV4Addr) noexcept
198 : addr_(ipV4Addr), family_(AF_INET) {}
200 // public ipv4 constructor
201 IPAddress::IPAddress(const in_addr ipV4Addr) noexcept
202 : addr_(IPAddressV4(ipV4Addr)), family_(AF_INET) {}
204 // public ipv6 constructor
205 IPAddress::IPAddress(const IPAddressV6& ipV6Addr) noexcept
206 : addr_(ipV6Addr), family_(AF_INET6) {}
208 // public ipv6 constructor
209 IPAddress::IPAddress(const in6_addr& ipV6Addr) noexcept
210 : addr_(IPAddressV6(ipV6Addr)), family_(AF_INET6) {}
212 // Assign from V4 address
213 IPAddress& IPAddress::operator=(const IPAddressV4& ipv4_addr) noexcept {
214 addr_ = IPAddressV46(ipv4_addr);
219 // Assign from V6 address
220 IPAddress& IPAddress::operator=(const IPAddressV6& ipv6_addr) noexcept {
221 addr_ = IPAddressV46(ipv6_addr);
227 bool IPAddress::inSubnet(StringPiece cidrNetwork) const {
228 auto subnetInfo = IPAddress::createNetwork(cidrNetwork);
229 return inSubnet(subnetInfo.first, subnetInfo.second);
233 bool IPAddress::inSubnet(const IPAddress& subnet, uint8_t cidr) const {
234 if (bitCount() == subnet.bitCount()) {
236 return asV4().inSubnet(subnet.asV4(), cidr);
238 return asV6().inSubnet(subnet.asV6(), cidr);
241 // an IPv4 address can never belong in a IPv6 subnet unless the IPv6 is a 6to4
242 // address and vice-versa
244 const IPAddressV6& v6addr = asV6();
245 const IPAddressV4& v4subnet = subnet.asV4();
246 if (v6addr.is6To4()) {
247 return v6addr.getIPv4For6To4().inSubnet(v4subnet, cidr);
249 } else if (subnet.isV6()) {
250 const IPAddressV6& v6subnet = subnet.asV6();
251 const IPAddressV4& v4addr = asV4();
252 if (v6subnet.is6To4()) {
253 return v4addr.inSubnet(v6subnet.getIPv4For6To4(), cidr);
260 bool IPAddress::inSubnetWithMask(const IPAddress& subnet, ByteRange mask)
262 auto mkByteArray4 = [&]() -> ByteArray4 {
264 std::memcpy(ba.data(), mask.begin(), std::min<size_t>(mask.size(), 4));
268 if (bitCount() == subnet.bitCount()) {
270 return asV4().inSubnetWithMask(subnet.asV4(), mkByteArray4());
273 std::memcpy(ba.data(), mask.begin(), std::min<size_t>(mask.size(), 16));
274 return asV6().inSubnetWithMask(subnet.asV6(), ba);
278 // an IPv4 address can never belong in a IPv6 subnet unless the IPv6 is a 6to4
279 // address and vice-versa
281 const IPAddressV6& v6addr = asV6();
282 const IPAddressV4& v4subnet = subnet.asV4();
283 if (v6addr.is6To4()) {
284 return v6addr.getIPv4For6To4().inSubnetWithMask(v4subnet, mkByteArray4());
286 } else if (subnet.isV6()) {
287 const IPAddressV6& v6subnet = subnet.asV6();
288 const IPAddressV4& v4addr = asV4();
289 if (v6subnet.is6To4()) {
290 return v4addr.inSubnetWithMask(v6subnet.getIPv4For6To4(), mkByteArray4());
296 uint8_t IPAddress::getNthMSByte(size_t byteIndex) const {
297 const auto highestIndex = byteCount() - 1;
298 if (byteIndex > highestIndex) {
299 throw std::invalid_argument(sformat(
300 "Byte index must be <= {} for addresses of type: {}",
302 detail::familyNameStr(family())));
305 return asV4().bytes()[byteIndex];
307 return asV6().bytes()[byteIndex];
311 bool operator==(const IPAddress& addr1, const IPAddress& addr2) {
312 if (addr1.family() == addr2.family()) {
314 return (addr1.asV6() == addr2.asV6());
315 } else if (addr1.isV4()) {
316 return (addr1.asV4() == addr2.asV4());
318 CHECK_EQ(addr1.family(), AF_UNSPEC);
319 // Two default initialized AF_UNSPEC addresses should be considered equal.
320 // AF_UNSPEC is the only other value for which an IPAddress can be
321 // created, in the default constructor case.
325 // addr1 is v4 mapped v6 address, addr2 is v4
326 if (addr1.isIPv4Mapped() && addr2.isV4()) {
327 if (IPAddress::createIPv4(addr1) == addr2.asV4()) {
331 // addr2 is v4 mapped v6 address, addr1 is v4
332 if (addr2.isIPv4Mapped() && addr1.isV4()) {
333 if (IPAddress::createIPv4(addr2) == addr1.asV4()) {
337 // we only compare IPv4 and IPv6 addresses
341 bool operator<(const IPAddress& addr1, const IPAddress& addr2) {
342 if (addr1.family() == addr2.family()) {
344 return (addr1.asV6() < addr2.asV6());
345 } else if (addr1.isV4()) {
346 return (addr1.asV4() < addr2.asV4());
348 CHECK_EQ(addr1.family(), AF_UNSPEC);
349 // Two default initialized AF_UNSPEC addresses can not be less than each
350 // other. AF_UNSPEC is the only other value for which an IPAddress can be
351 // created, in the default constructor case.
356 // means addr2 is v4, convert it to a mapped v6 address and compare
357 return addr1.asV6() < addr2.asV4().createIPv6();
360 // means addr2 is v6, convert addr1 to v4 mapped and compare
361 return addr1.asV4().createIPv6() < addr2.asV6();
366 CIDRNetwork IPAddress::longestCommonPrefix(
367 const CIDRNetwork& one,
368 const CIDRNetwork& two) {
369 if (one.first.family() != two.first.family()) {
370 throw std::invalid_argument(sformat(
371 "Can't compute longest common prefix between addresses of different"
372 "families. Passed: {} and {}",
373 detail::familyNameStr(one.first.family()),
374 detail::familyNameStr(two.first.family())));
376 if (one.first.isV4()) {
377 auto prefix = IPAddressV4::longestCommonPrefix(
378 {one.first.asV4(), one.second}, {two.first.asV4(), two.second});
379 return {IPAddress(prefix.first), prefix.second};
380 } else if (one.first.isV6()) {
381 auto prefix = IPAddressV6::longestCommonPrefix(
382 {one.first.asV6(), one.second}, {two.first.asV6(), two.second});
383 return {IPAddress(prefix.first), prefix.second};
385 throw std::invalid_argument("Unknown address family");
389 [[noreturn]] void IPAddress::asV4Throw() const {
390 auto fam = detail::familyNameStr(family());
391 throw InvalidAddressFamilyException(
392 sformat("Can't convert address with family {} to AF_INET address", fam));
395 [[noreturn]] void IPAddress::asV6Throw() const {
396 auto fam = detail::familyNameStr(family());
397 throw InvalidAddressFamilyException(
398 sformat("Can't convert address with family {} to AF_INET6 address", fam));