2 * Copyright 2016 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));
92 uint8_t cidr = (defaultCidr > -1) ? defaultCidr : (subnet.isV4() ? 32 : 128);
96 cidr = to<uint8_t>(vec.at(1));
98 throw IPAddressFormatException(
99 to<std::string>("Mask value ", "'", vec.at(1), "' not a valid mask"));
102 if (cidr > subnet.bitCount()) {
103 throw IPAddressFormatException(to<std::string>(
107 "is > network bit count ",
112 return std::make_pair(applyMask ? subnet.mask(cidr) : subnet, cidr);
116 std::string IPAddress::networkToString(const CIDRNetwork& network) {
117 return network.first.str() + "/" + folly::to<std::string>(network.second);
121 IPAddress IPAddress::fromBinary(ByteRange bytes) {
122 if (bytes.size() == 4) {
123 return IPAddress(IPAddressV4::fromBinary(bytes));
124 } else if (bytes.size() == 16) {
125 return IPAddress(IPAddressV6::fromBinary(bytes));
127 string hexval = detail::Bytes::toHex(bytes.data(), bytes.size());
128 throw IPAddressFormatException(
129 to<std::string>("Invalid address with hex value ", "'", hexval, "'"));
134 IPAddress IPAddress::fromLong(uint32_t src) {
135 return IPAddress(IPAddressV4::fromLong(src));
137 IPAddress IPAddress::fromLongHBO(uint32_t src) {
138 return IPAddress(IPAddressV4::fromLongHBO(src));
141 // default constructor
142 IPAddress::IPAddress()
148 // public string constructor
149 IPAddress::IPAddress(StringPiece addr)
153 string ip = addr.str(); // inet_pton() needs NUL-terminated string
154 auto throwFormatException = [&](const string& msg) {
155 throw IPAddressFormatException(
156 to<std::string>("Invalid IP '", ip, "': ", msg));
160 throwFormatException("address too short");
162 if (ip.front() == '[' && ip.back() == ']') {
163 ip = ip.substr(1, ip.size() - 2);
166 // need to check for V4 address second, since IPv4-mapped IPv6 addresses may
168 if (ip.find(':') != string::npos) {
169 struct addrinfo* result;
170 struct addrinfo hints;
171 memset(&hints, 0, sizeof(hints));
172 hints.ai_family = AF_INET6;
173 hints.ai_socktype = SOCK_STREAM;
174 hints.ai_flags = AI_NUMERICHOST;
175 if (!getaddrinfo(ip.c_str(), nullptr, &hints, &result)) {
176 struct sockaddr_in6* ipAddr = (struct sockaddr_in6*)result->ai_addr;
177 addr_ = IPAddressV46(IPAddressV6(*ipAddr));
179 freeaddrinfo(result);
181 throwFormatException("getsockaddr failed for V6 address");
183 } else if (ip.find('.') != string::npos) {
185 if (inet_pton(AF_INET, ip.c_str(), &ipAddr) != 1) {
186 throwFormatException("inet_pton failed for V4 address");
188 addr_ = IPAddressV46(IPAddressV4(ipAddr));
191 throwFormatException("invalid address format");
195 // public sockaddr constructor
196 IPAddress::IPAddress(const sockaddr* addr)
200 if (addr == nullptr) {
201 throw IPAddressFormatException("sockaddr == nullptr");
203 family_ = addr->sa_family;
204 switch (addr->sa_family) {
206 const sockaddr_in *v4addr = reinterpret_cast<const sockaddr_in*>(addr);
207 addr_.ipV4Addr = IPAddressV4(v4addr->sin_addr);
211 const sockaddr_in6 *v6addr = reinterpret_cast<const sockaddr_in6*>(addr);
212 addr_.ipV6Addr = IPAddressV6(*v6addr);
216 throw InvalidAddressFamilyException(addr->sa_family);
220 // public ipv4 constructor
221 IPAddress::IPAddress(const IPAddressV4 ipV4Addr)
227 // public ipv4 constructor
228 IPAddress::IPAddress(const in_addr ipV4Addr)
229 : addr_(IPAddressV4(ipV4Addr))
234 // public ipv6 constructor
235 IPAddress::IPAddress(const IPAddressV6& ipV6Addr)
241 // public ipv6 constructor
242 IPAddress::IPAddress(const in6_addr& ipV6Addr)
243 : addr_(IPAddressV6(ipV6Addr))
248 // Assign from V4 address
249 IPAddress& IPAddress::operator=(const IPAddressV4& ipv4_addr) {
250 addr_ = IPAddressV46(ipv4_addr);
255 // Assign from V6 address
256 IPAddress& IPAddress::operator=(const IPAddressV6& ipv6_addr) {
257 addr_ = IPAddressV46(ipv6_addr);
263 bool IPAddress::inSubnet(StringPiece cidrNetwork) const {
264 auto subnetInfo = IPAddress::createNetwork(cidrNetwork);
265 return inSubnet(subnetInfo.first, subnetInfo.second);
269 bool IPAddress::inSubnet(const IPAddress& subnet, uint8_t cidr) const {
270 if (bitCount() == subnet.bitCount()) {
272 return asV4().inSubnet(subnet.asV4(), cidr);
274 return asV6().inSubnet(subnet.asV6(), cidr);
277 // an IPv4 address can never belong in a IPv6 subnet unless the IPv6 is a 6to4
278 // address and vice-versa
280 const IPAddressV6& v6addr = asV6();
281 const IPAddressV4& v4subnet = subnet.asV4();
282 if (v6addr.is6To4()) {
283 return v6addr.getIPv4For6To4().inSubnet(v4subnet, cidr);
285 } else if (subnet.isV6()) {
286 const IPAddressV6& v6subnet = subnet.asV6();
287 const IPAddressV4& v4addr = asV4();
288 if (v6subnet.is6To4()) {
289 return v4addr.inSubnet(v6subnet.getIPv4For6To4(), cidr);
296 bool IPAddress::inSubnetWithMask(const IPAddress& subnet,
297 ByteRange mask) const {
298 auto mkByteArray4 = [&]() -> ByteArray4 {
300 std::memcpy(ba.data(), mask.begin(), std::min<size_t>(mask.size(), 4));
304 if (bitCount() == subnet.bitCount()) {
306 return asV4().inSubnetWithMask(subnet.asV4(), mkByteArray4());
309 std::memcpy(ba.data(), mask.begin(), std::min<size_t>(mask.size(), 16));
310 return asV6().inSubnetWithMask(subnet.asV6(), ba);
314 // an IPv4 address can never belong in a IPv6 subnet unless the IPv6 is a 6to4
315 // address and vice-versa
317 const IPAddressV6& v6addr = asV6();
318 const IPAddressV4& v4subnet = subnet.asV4();
319 if (v6addr.is6To4()) {
320 return v6addr.getIPv4For6To4().inSubnetWithMask(v4subnet, mkByteArray4());
322 } else if (subnet.isV6()) {
323 const IPAddressV6& v6subnet = subnet.asV6();
324 const IPAddressV4& v4addr = asV4();
325 if (v6subnet.is6To4()) {
326 return v4addr.inSubnetWithMask(v6subnet.getIPv4For6To4(), mkByteArray4());
332 uint8_t IPAddress::getNthMSByte(size_t byteIndex) const {
333 const auto highestIndex = byteCount() - 1;
334 if (byteIndex > highestIndex) {
335 throw std::invalid_argument(to<string>("Byte index must be <= ",
336 to<string>(highestIndex), " for addresses of type :",
337 detail::familyNameStr(family())));
340 return asV4().bytes()[byteIndex];
342 return asV6().bytes()[byteIndex];
346 bool operator==(const IPAddress& addr1, const IPAddress& addr2) {
347 if (addr1.family() == addr2.family()) {
349 return (addr1.asV6() == addr2.asV6());
350 } else if (addr1.isV4()) {
351 return (addr1.asV4() == addr2.asV4());
353 CHECK_EQ(addr1.family(), AF_UNSPEC);
354 // Two default initialized AF_UNSPEC addresses should be considered equal.
355 // AF_UNSPEC is the only other value for which an IPAddress can be
356 // created, in the default constructor case.
360 // addr1 is v4 mapped v6 address, addr2 is v4
361 if (addr1.isIPv4Mapped() && addr2.isV4()) {
362 if (IPAddress::createIPv4(addr1) == addr2.asV4()) {
366 // addr2 is v4 mapped v6 address, addr1 is v4
367 if (addr2.isIPv4Mapped() && addr1.isV4()) {
368 if (IPAddress::createIPv4(addr2) == addr1.asV4()) {
372 // we only compare IPv4 and IPv6 addresses
376 bool operator<(const IPAddress& addr1, const IPAddress& addr2) {
377 if (addr1.family() == addr2.family()) {
379 return (addr1.asV6() < addr2.asV6());
380 } else if (addr1.isV4()) {
381 return (addr1.asV4() < addr2.asV4());
383 CHECK_EQ(addr1.family(), AF_UNSPEC);
384 // Two default initialized AF_UNSPEC addresses can not be less than each
385 // other. AF_UNSPEC is the only other value for which an IPAddress can be
386 // created, in the default constructor case.
391 // means addr2 is v4, convert it to a mapped v6 address and compare
392 return addr1.asV6() < addr2.asV4().createIPv6();
395 // means addr2 is v6, convert addr1 to v4 mapped and compare
396 return addr1.asV4().createIPv6() < addr2.asV6();
402 IPAddress::longestCommonPrefix(const CIDRNetwork& one, const CIDRNetwork& two) {
403 if (one.first.family() != two.first.family()) {
404 throw std::invalid_argument(to<string>("Can't compute "
405 "longest common prefix between addresses of different families. "
406 "Passed: ", detail::familyNameStr(one.first.family()), " and ",
407 detail::familyNameStr(two.first.family())));
409 if (one.first.isV4()) {
410 auto prefix = IPAddressV4::longestCommonPrefix(
411 {one.first.asV4(), one.second},
412 {two.first.asV4(), two.second});
413 return {IPAddress(prefix.first), prefix.second};
414 } else if (one.first.isV6()) {
415 auto prefix = IPAddressV6::longestCommonPrefix(
416 {one.first.asV6(), one.second},
417 {two.first.asV6(), two.second});
418 return {IPAddress(prefix.first), prefix.second};
420 throw std::invalid_argument("Unknown address family");
422 return {IPAddress(0), 0};
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"));