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/Conv.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) {
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(StringPiece ipSlashCidr,
73 int defaultCidr, /* = -1 */
74 bool applyMask /* = true */) {
75 if (defaultCidr > std::numeric_limits<uint8_t>::max()) {
76 throw std::range_error("defaultCidr must be <= UINT8_MAX");
79 split("/", ipSlashCidr, vec);
80 vector<string>::size_type elemCount = vec.size();
82 if (elemCount == 0 || // weird invalid string
83 elemCount > 2) { // invalid string (IP/CIDR/extras)
84 throw IPAddressFormatException(to<std::string>(
85 "Invalid ipSlashCidr specified. ",
86 "Expected IP/CIDR format, got ",
91 IPAddress subnet(vec.at(0));
93 (defaultCidr > -1) ? uint8_t(defaultCidr) : (subnet.isV4() ? 32 : 128);
97 cidr = to<uint8_t>(vec.at(1));
99 throw IPAddressFormatException(
100 to<std::string>("Mask value ", "'", vec.at(1), "' not a valid mask"));
103 if (cidr > subnet.bitCount()) {
104 throw IPAddressFormatException(to<std::string>(
108 "is > network bit count ",
113 return std::make_pair(applyMask ? subnet.mask(cidr) : subnet, cidr);
117 std::string IPAddress::networkToString(const CIDRNetwork& network) {
118 return network.first.str() + "/" + folly::to<std::string>(network.second);
122 IPAddress IPAddress::fromBinary(ByteRange bytes) {
123 if (bytes.size() == 4) {
124 return IPAddress(IPAddressV4::fromBinary(bytes));
125 } else if (bytes.size() == 16) {
126 return IPAddress(IPAddressV6::fromBinary(bytes));
128 string hexval = detail::Bytes::toHex(bytes.data(), bytes.size());
129 throw IPAddressFormatException(
130 to<std::string>("Invalid address with hex value ", "'", hexval, "'"));
135 IPAddress IPAddress::fromLong(uint32_t src) {
136 return IPAddress(IPAddressV4::fromLong(src));
138 IPAddress IPAddress::fromLongHBO(uint32_t src) {
139 return IPAddress(IPAddressV4::fromLongHBO(src));
142 // default constructor
143 IPAddress::IPAddress()
149 // public string constructor
150 IPAddress::IPAddress(StringPiece addr)
154 string ip = addr.str(); // inet_pton() needs NUL-terminated string
155 auto throwFormatException = [&](const string& msg) {
156 throw IPAddressFormatException(
157 to<std::string>("Invalid IP '", ip, "': ", msg));
161 throwFormatException("address too short");
163 if (ip.front() == '[' && ip.back() == ']') {
164 ip = ip.substr(1, ip.size() - 2);
167 // need to check for V4 address second, since IPv4-mapped IPv6 addresses may
169 if (ip.find(':') != string::npos) {
170 struct addrinfo* result;
171 struct addrinfo hints;
172 memset(&hints, 0, sizeof(hints));
173 hints.ai_family = AF_INET6;
174 hints.ai_socktype = SOCK_STREAM;
175 hints.ai_flags = AI_NUMERICHOST;
176 if (!getaddrinfo(ip.c_str(), nullptr, &hints, &result)) {
177 struct sockaddr_in6* ipAddr = (struct sockaddr_in6*)result->ai_addr;
178 addr_ = IPAddressV46(IPAddressV6(*ipAddr));
180 freeaddrinfo(result);
182 throwFormatException("getsockaddr failed for V6 address");
184 } else if (ip.find('.') != string::npos) {
186 if (inet_pton(AF_INET, ip.c_str(), &ipAddr) != 1) {
187 throwFormatException("inet_pton failed for V4 address");
189 addr_ = IPAddressV46(IPAddressV4(ipAddr));
192 throwFormatException("invalid address format");
196 // public sockaddr constructor
197 IPAddress::IPAddress(const sockaddr* addr)
201 if (addr == nullptr) {
202 throw IPAddressFormatException("sockaddr == nullptr");
204 family_ = addr->sa_family;
205 switch (addr->sa_family) {
207 const sockaddr_in *v4addr = reinterpret_cast<const sockaddr_in*>(addr);
208 addr_.ipV4Addr = IPAddressV4(v4addr->sin_addr);
212 const sockaddr_in6 *v6addr = reinterpret_cast<const sockaddr_in6*>(addr);
213 addr_.ipV6Addr = IPAddressV6(*v6addr);
217 throw InvalidAddressFamilyException(addr->sa_family);
221 // public ipv4 constructor
222 IPAddress::IPAddress(const IPAddressV4 ipV4Addr)
228 // public ipv4 constructor
229 IPAddress::IPAddress(const in_addr ipV4Addr)
230 : addr_(IPAddressV4(ipV4Addr))
235 // public ipv6 constructor
236 IPAddress::IPAddress(const IPAddressV6& ipV6Addr)
242 // public ipv6 constructor
243 IPAddress::IPAddress(const in6_addr& ipV6Addr)
244 : addr_(IPAddressV6(ipV6Addr))
249 // Assign from V4 address
250 IPAddress& IPAddress::operator=(const IPAddressV4& ipv4_addr) {
251 addr_ = IPAddressV46(ipv4_addr);
256 // Assign from V6 address
257 IPAddress& IPAddress::operator=(const IPAddressV6& ipv6_addr) {
258 addr_ = IPAddressV46(ipv6_addr);
264 bool IPAddress::inSubnet(StringPiece cidrNetwork) const {
265 auto subnetInfo = IPAddress::createNetwork(cidrNetwork);
266 return inSubnet(subnetInfo.first, subnetInfo.second);
270 bool IPAddress::inSubnet(const IPAddress& subnet, uint8_t cidr) const {
271 if (bitCount() == subnet.bitCount()) {
273 return asV4().inSubnet(subnet.asV4(), cidr);
275 return asV6().inSubnet(subnet.asV6(), cidr);
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().inSubnet(v4subnet, cidr);
286 } else if (subnet.isV6()) {
287 const IPAddressV6& v6subnet = subnet.asV6();
288 const IPAddressV4& v4addr = asV4();
289 if (v6subnet.is6To4()) {
290 return v4addr.inSubnet(v6subnet.getIPv4For6To4(), cidr);
297 bool IPAddress::inSubnetWithMask(const IPAddress& subnet,
298 ByteRange mask) const {
299 auto mkByteArray4 = [&]() -> ByteArray4 {
301 std::memcpy(ba.data(), mask.begin(), std::min<size_t>(mask.size(), 4));
305 if (bitCount() == subnet.bitCount()) {
307 return asV4().inSubnetWithMask(subnet.asV4(), mkByteArray4());
310 std::memcpy(ba.data(), mask.begin(), std::min<size_t>(mask.size(), 16));
311 return asV6().inSubnetWithMask(subnet.asV6(), ba);
315 // an IPv4 address can never belong in a IPv6 subnet unless the IPv6 is a 6to4
316 // address and vice-versa
318 const IPAddressV6& v6addr = asV6();
319 const IPAddressV4& v4subnet = subnet.asV4();
320 if (v6addr.is6To4()) {
321 return v6addr.getIPv4For6To4().inSubnetWithMask(v4subnet, mkByteArray4());
323 } else if (subnet.isV6()) {
324 const IPAddressV6& v6subnet = subnet.asV6();
325 const IPAddressV4& v4addr = asV4();
326 if (v6subnet.is6To4()) {
327 return v4addr.inSubnetWithMask(v6subnet.getIPv4For6To4(), mkByteArray4());
333 uint8_t IPAddress::getNthMSByte(size_t byteIndex) const {
334 const auto highestIndex = byteCount() - 1;
335 if (byteIndex > highestIndex) {
336 throw std::invalid_argument(to<string>("Byte index must be <= ",
337 to<string>(highestIndex), " for addresses of type :",
338 detail::familyNameStr(family())));
341 return asV4().bytes()[byteIndex];
343 return asV6().bytes()[byteIndex];
347 bool operator==(const IPAddress& addr1, const IPAddress& addr2) {
348 if (addr1.family() == addr2.family()) {
350 return (addr1.asV6() == addr2.asV6());
351 } else if (addr1.isV4()) {
352 return (addr1.asV4() == addr2.asV4());
354 CHECK_EQ(addr1.family(), AF_UNSPEC);
355 // Two default initialized AF_UNSPEC addresses should be considered equal.
356 // AF_UNSPEC is the only other value for which an IPAddress can be
357 // created, in the default constructor case.
361 // addr1 is v4 mapped v6 address, addr2 is v4
362 if (addr1.isIPv4Mapped() && addr2.isV4()) {
363 if (IPAddress::createIPv4(addr1) == addr2.asV4()) {
367 // addr2 is v4 mapped v6 address, addr1 is v4
368 if (addr2.isIPv4Mapped() && addr1.isV4()) {
369 if (IPAddress::createIPv4(addr2) == addr1.asV4()) {
373 // we only compare IPv4 and IPv6 addresses
377 bool operator<(const IPAddress& addr1, const IPAddress& addr2) {
378 if (addr1.family() == addr2.family()) {
380 return (addr1.asV6() < addr2.asV6());
381 } else if (addr1.isV4()) {
382 return (addr1.asV4() < addr2.asV4());
384 CHECK_EQ(addr1.family(), AF_UNSPEC);
385 // Two default initialized AF_UNSPEC addresses can not be less than each
386 // other. AF_UNSPEC is the only other value for which an IPAddress can be
387 // created, in the default constructor case.
392 // means addr2 is v4, convert it to a mapped v6 address and compare
393 return addr1.asV6() < addr2.asV4().createIPv6();
396 // means addr2 is v6, convert addr1 to v4 mapped and compare
397 return addr1.asV4().createIPv6() < addr2.asV6();
403 IPAddress::longestCommonPrefix(const CIDRNetwork& one, const CIDRNetwork& two) {
404 if (one.first.family() != two.first.family()) {
405 throw std::invalid_argument(to<string>("Can't compute "
406 "longest common prefix between addresses of different families. "
407 "Passed: ", detail::familyNameStr(one.first.family()), " and ",
408 detail::familyNameStr(two.first.family())));
410 if (one.first.isV4()) {
411 auto prefix = IPAddressV4::longestCommonPrefix(
412 {one.first.asV4(), one.second},
413 {two.first.asV4(), two.second});
414 return {IPAddress(prefix.first), prefix.second};
415 } else if (one.first.isV6()) {
416 auto prefix = IPAddressV6::longestCommonPrefix(
417 {one.first.asV6(), one.second},
418 {two.first.asV6(), two.second});
419 return {IPAddress(prefix.first), prefix.second};
421 throw std::invalid_argument("Unknown address family");
425 [[noreturn]] void IPAddress::asV4Throw() const {
426 auto fam = detail::familyNameStr(family());
427 throw InvalidAddressFamilyException(to<std::string>(
428 "Can't convert address with family ", fam, " to AF_INET address"));
431 [[noreturn]] void IPAddress::asV6Throw() const {
432 auto fam = detail::familyNameStr(family());
433 throw InvalidAddressFamilyException(to<std::string>(
434 "Can't convert address with family ", fam, " to AF_INET6 address"));