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) {
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));
129 IPAddress IPAddress::fromLong(uint32_t src) {
130 return IPAddress(IPAddressV4::fromLong(src));
132 IPAddress IPAddress::fromLongHBO(uint32_t src) {
133 return IPAddress(IPAddressV4::fromLongHBO(src));
136 // default constructor
137 IPAddress::IPAddress() : addr_(), family_(AF_UNSPEC) {}
139 // public string constructor
140 IPAddress::IPAddress(StringPiece addr) : addr_(), family_(AF_UNSPEC) {
141 string ip = addr.str(); // inet_pton() needs NUL-terminated string
142 auto throwFormatException = [&](const string& msg) {
143 throw IPAddressFormatException(sformat("Invalid IP '{}': {}", ip, msg));
147 throwFormatException("address too short");
149 if (ip.front() == '[' && ip.back() == ']') {
150 ip = ip.substr(1, ip.size() - 2);
153 // need to check for V4 address second, since IPv4-mapped IPv6 addresses may
155 if (ip.find(':') != string::npos) {
156 struct addrinfo* result;
157 struct addrinfo hints;
158 memset(&hints, 0, sizeof(hints));
159 hints.ai_family = AF_INET6;
160 hints.ai_socktype = SOCK_STREAM;
161 hints.ai_flags = AI_NUMERICHOST;
162 if (!getaddrinfo(ip.c_str(), nullptr, &hints, &result)) {
163 struct sockaddr_in6* ipAddr = (struct sockaddr_in6*)result->ai_addr;
164 addr_ = IPAddressV46(IPAddressV6(*ipAddr));
166 freeaddrinfo(result);
168 throwFormatException("getsockaddr failed for V6 address");
170 } else if (ip.find('.') != string::npos) {
172 if (inet_pton(AF_INET, ip.c_str(), &ipAddr) != 1) {
173 throwFormatException("inet_pton failed for V4 address");
175 addr_ = IPAddressV46(IPAddressV4(ipAddr));
178 throwFormatException("invalid address format");
182 // public sockaddr constructor
183 IPAddress::IPAddress(const sockaddr* addr) : addr_(), family_(AF_UNSPEC) {
184 if (addr == nullptr) {
185 throw IPAddressFormatException("sockaddr == nullptr");
187 family_ = addr->sa_family;
188 switch (addr->sa_family) {
190 const sockaddr_in* v4addr = reinterpret_cast<const sockaddr_in*>(addr);
191 addr_.ipV4Addr = IPAddressV4(v4addr->sin_addr);
195 const sockaddr_in6* v6addr = reinterpret_cast<const sockaddr_in6*>(addr);
196 addr_.ipV6Addr = IPAddressV6(*v6addr);
200 throw InvalidAddressFamilyException(addr->sa_family);
204 // public ipv4 constructor
205 IPAddress::IPAddress(const IPAddressV4 ipV4Addr)
206 : addr_(ipV4Addr), family_(AF_INET) {}
208 // public ipv4 constructor
209 IPAddress::IPAddress(const in_addr ipV4Addr)
210 : addr_(IPAddressV4(ipV4Addr)), family_(AF_INET) {}
212 // public ipv6 constructor
213 IPAddress::IPAddress(const IPAddressV6& ipV6Addr)
214 : addr_(ipV6Addr), family_(AF_INET6) {}
216 // public ipv6 constructor
217 IPAddress::IPAddress(const in6_addr& ipV6Addr)
218 : addr_(IPAddressV6(ipV6Addr)), family_(AF_INET6) {}
220 // Assign from V4 address
221 IPAddress& IPAddress::operator=(const IPAddressV4& ipv4_addr) {
222 addr_ = IPAddressV46(ipv4_addr);
227 // Assign from V6 address
228 IPAddress& IPAddress::operator=(const IPAddressV6& ipv6_addr) {
229 addr_ = IPAddressV46(ipv6_addr);
235 bool IPAddress::inSubnet(StringPiece cidrNetwork) const {
236 auto subnetInfo = IPAddress::createNetwork(cidrNetwork);
237 return inSubnet(subnetInfo.first, subnetInfo.second);
241 bool IPAddress::inSubnet(const IPAddress& subnet, uint8_t cidr) const {
242 if (bitCount() == subnet.bitCount()) {
244 return asV4().inSubnet(subnet.asV4(), cidr);
246 return asV6().inSubnet(subnet.asV6(), cidr);
249 // an IPv4 address can never belong in a IPv6 subnet unless the IPv6 is a 6to4
250 // address and vice-versa
252 const IPAddressV6& v6addr = asV6();
253 const IPAddressV4& v4subnet = subnet.asV4();
254 if (v6addr.is6To4()) {
255 return v6addr.getIPv4For6To4().inSubnet(v4subnet, cidr);
257 } else if (subnet.isV6()) {
258 const IPAddressV6& v6subnet = subnet.asV6();
259 const IPAddressV4& v4addr = asV4();
260 if (v6subnet.is6To4()) {
261 return v4addr.inSubnet(v6subnet.getIPv4For6To4(), cidr);
268 bool IPAddress::inSubnetWithMask(const IPAddress& subnet, ByteRange mask)
270 auto mkByteArray4 = [&]() -> ByteArray4 {
272 std::memcpy(ba.data(), mask.begin(), std::min<size_t>(mask.size(), 4));
276 if (bitCount() == subnet.bitCount()) {
278 return asV4().inSubnetWithMask(subnet.asV4(), mkByteArray4());
281 std::memcpy(ba.data(), mask.begin(), std::min<size_t>(mask.size(), 16));
282 return asV6().inSubnetWithMask(subnet.asV6(), ba);
286 // an IPv4 address can never belong in a IPv6 subnet unless the IPv6 is a 6to4
287 // address and vice-versa
289 const IPAddressV6& v6addr = asV6();
290 const IPAddressV4& v4subnet = subnet.asV4();
291 if (v6addr.is6To4()) {
292 return v6addr.getIPv4For6To4().inSubnetWithMask(v4subnet, mkByteArray4());
294 } else if (subnet.isV6()) {
295 const IPAddressV6& v6subnet = subnet.asV6();
296 const IPAddressV4& v4addr = asV4();
297 if (v6subnet.is6To4()) {
298 return v4addr.inSubnetWithMask(v6subnet.getIPv4For6To4(), mkByteArray4());
304 uint8_t IPAddress::getNthMSByte(size_t byteIndex) const {
305 const auto highestIndex = byteCount() - 1;
306 if (byteIndex > highestIndex) {
307 throw std::invalid_argument(sformat(
308 "Byte index must be <= {} for addresses of type: {}",
310 detail::familyNameStr(family())));
313 return asV4().bytes()[byteIndex];
315 return asV6().bytes()[byteIndex];
319 bool operator==(const IPAddress& addr1, const IPAddress& addr2) {
320 if (addr1.family() == addr2.family()) {
322 return (addr1.asV6() == addr2.asV6());
323 } else if (addr1.isV4()) {
324 return (addr1.asV4() == addr2.asV4());
326 CHECK_EQ(addr1.family(), AF_UNSPEC);
327 // Two default initialized AF_UNSPEC addresses should be considered equal.
328 // AF_UNSPEC is the only other value for which an IPAddress can be
329 // created, in the default constructor case.
333 // addr1 is v4 mapped v6 address, addr2 is v4
334 if (addr1.isIPv4Mapped() && addr2.isV4()) {
335 if (IPAddress::createIPv4(addr1) == addr2.asV4()) {
339 // addr2 is v4 mapped v6 address, addr1 is v4
340 if (addr2.isIPv4Mapped() && addr1.isV4()) {
341 if (IPAddress::createIPv4(addr2) == addr1.asV4()) {
345 // we only compare IPv4 and IPv6 addresses
349 bool operator<(const IPAddress& addr1, const IPAddress& addr2) {
350 if (addr1.family() == addr2.family()) {
352 return (addr1.asV6() < addr2.asV6());
353 } else if (addr1.isV4()) {
354 return (addr1.asV4() < addr2.asV4());
356 CHECK_EQ(addr1.family(), AF_UNSPEC);
357 // Two default initialized AF_UNSPEC addresses can not be less than each
358 // other. AF_UNSPEC is the only other value for which an IPAddress can be
359 // created, in the default constructor case.
364 // means addr2 is v4, convert it to a mapped v6 address and compare
365 return addr1.asV6() < addr2.asV4().createIPv6();
368 // means addr2 is v6, convert addr1 to v4 mapped and compare
369 return addr1.asV4().createIPv6() < addr2.asV6();
374 CIDRNetwork IPAddress::longestCommonPrefix(
375 const CIDRNetwork& one,
376 const CIDRNetwork& two) {
377 if (one.first.family() != two.first.family()) {
378 throw std::invalid_argument(sformat(
379 "Can't compute longest common prefix between addresses of different"
380 "families. Passed: {} and {}",
381 detail::familyNameStr(one.first.family()),
382 detail::familyNameStr(two.first.family())));
384 if (one.first.isV4()) {
385 auto prefix = IPAddressV4::longestCommonPrefix(
386 {one.first.asV4(), one.second}, {two.first.asV4(), two.second});
387 return {IPAddress(prefix.first), prefix.second};
388 } else if (one.first.isV6()) {
389 auto prefix = IPAddressV6::longestCommonPrefix(
390 {one.first.asV6(), one.second}, {two.first.asV6(), two.second});
391 return {IPAddress(prefix.first), prefix.second};
393 throw std::invalid_argument("Unknown address family");
397 [[noreturn]] void IPAddress::asV4Throw() const {
398 auto fam = detail::familyNameStr(family());
399 throw InvalidAddressFamilyException(
400 sformat("Can't convert address with family {} to AF_INET address", fam));
403 [[noreturn]] void IPAddress::asV6Throw() const {
404 auto fam = detail::familyNameStr(family());
405 throw InvalidAddressFamilyException(
406 sformat("Can't convert address with family {} to AF_INET6 address", fam));