2 * Copyright 2015 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/String.h>
33 size_t hash_value(const IPAddress& addr) {
36 ostream& operator<<(ostream& os, const IPAddress& addr) {
40 void toAppend(IPAddress addr, string* result) {
41 result->append(addr.str());
43 void toAppend(IPAddress addr, fbstring* result) {
44 result->append(addr.str());
48 IPAddressV4 IPAddress::createIPv4(const IPAddress& addr) {
52 return addr.asV6().createIPv4();
57 IPAddressV6 IPAddress::createIPv6(const IPAddress& addr) {
61 return addr.asV4().createIPv6();
66 CIDRNetwork IPAddress::createNetwork(StringPiece ipSlashCidr,
67 int defaultCidr, /* = -1 */
68 bool applyMask /* = true */) {
69 if (defaultCidr > std::numeric_limits<uint8_t>::max()) {
70 throw std::range_error("defaultCidr must be <= UINT8_MAX");
73 split("/", ipSlashCidr, vec);
74 vector<string>::size_type elemCount = vec.size();
76 if (elemCount == 0 || // weird invalid string
77 elemCount > 2) { // invalid string (IP/CIDR/extras)
78 throw IPAddressFormatException("Invalid ipSlashCidr specified. ",
79 "Expected IP/CIDR format, got ",
80 "'", ipSlashCidr, "'");
82 IPAddress subnet(vec.at(0));
83 uint8_t cidr = (defaultCidr > -1) ? defaultCidr : (subnet.isV4() ? 32 : 128);
87 cidr = to<uint8_t>(vec.at(1));
89 throw IPAddressFormatException("Mask value ",
90 "'", vec.at(1), "' not a valid mask");
93 if (cidr > subnet.bitCount()) {
94 throw IPAddressFormatException("CIDR value '", cidr, "' ",
95 "is > network bit count ",
96 "'", subnet.bitCount(), "'");
98 return std::make_pair(applyMask ? subnet.mask(cidr) : subnet, cidr);
102 IPAddress IPAddress::fromBinary(ByteRange bytes) {
103 if (bytes.size() == 4) {
104 return IPAddress(IPAddressV4::fromBinary(bytes));
105 } else if (bytes.size() == 16) {
106 return IPAddress(IPAddressV6::fromBinary(bytes));
108 string hexval = detail::Bytes::toHex(bytes.data(), bytes.size());
109 throw IPAddressFormatException("Invalid address with hex value ",
115 IPAddress IPAddress::fromLong(uint32_t src) {
116 return IPAddress(IPAddressV4::fromLong(src));
118 IPAddress IPAddress::fromLongHBO(uint32_t src) {
119 return IPAddress(IPAddressV4::fromLongHBO(src));
122 // default constructor
123 IPAddress::IPAddress()
129 // public string constructor
130 IPAddress::IPAddress(StringPiece addr)
134 string ip = addr.str(); // inet_pton() needs NUL-terminated string
135 auto throwFormatException = [&](const string& msg) {
136 throw IPAddressFormatException("Invalid IP '", ip, "': ", msg);
140 throwFormatException("address too short");
142 if (ip.front() == '[' && ip.back() == ']') {
143 ip = ip.substr(1, ip.size() - 2);
146 // need to check for V4 address second, since IPv4-mapped IPv6 addresses may
148 if (ip.find(':') != string::npos) {
149 struct addrinfo* result;
150 struct addrinfo hints;
151 memset(&hints, 0, sizeof(hints));
152 hints.ai_family = AF_INET6;
153 hints.ai_socktype = SOCK_STREAM;
154 hints.ai_flags = AI_NUMERICHOST;
155 if (!getaddrinfo(ip.c_str(), nullptr, &hints, &result)) {
156 struct sockaddr_in6* ipAddr = (struct sockaddr_in6*)result->ai_addr;
157 addr_ = IPAddressV46(IPAddressV6(*ipAddr));
159 freeaddrinfo(result);
161 throwFormatException("getsockaddr failed for V6 address");
163 } else if (ip.find('.') != string::npos) {
165 if (inet_pton(AF_INET, ip.c_str(), &ipAddr) != 1) {
166 throwFormatException("inet_pton failed for V4 address");
168 addr_ = IPAddressV46(IPAddressV4(ipAddr));
171 throwFormatException("invalid address format");
175 // public sockaddr constructor
176 IPAddress::IPAddress(const sockaddr* addr)
180 if (addr == nullptr) {
181 throw IPAddressFormatException("sockaddr == nullptr");
183 family_ = addr->sa_family;
184 switch (addr->sa_family) {
186 const sockaddr_in *v4addr = reinterpret_cast<const sockaddr_in*>(addr);
187 addr_.ipV4Addr = IPAddressV4(v4addr->sin_addr);
191 const sockaddr_in6 *v6addr = reinterpret_cast<const sockaddr_in6*>(addr);
192 addr_.ipV6Addr = IPAddressV6(*v6addr);
196 throw InvalidAddressFamilyException(addr->sa_family);
200 // public ipv4 constructor
201 IPAddress::IPAddress(const IPAddressV4 ipV4Addr)
207 // public ipv4 constructor
208 IPAddress::IPAddress(const in_addr ipV4Addr)
209 : addr_(IPAddressV4(ipV4Addr))
214 // public ipv6 constructor
215 IPAddress::IPAddress(const IPAddressV6& ipV6Addr)
221 // public ipv6 constructor
222 IPAddress::IPAddress(const in6_addr& ipV6Addr)
223 : addr_(IPAddressV6(ipV6Addr))
228 // Assign from V4 address
229 IPAddress& IPAddress::operator=(const IPAddressV4& ipv4_addr) {
230 addr_ = IPAddressV46(ipv4_addr);
235 // Assign from V6 address
236 IPAddress& IPAddress::operator=(const IPAddressV6& ipv6_addr) {
237 addr_ = IPAddressV46(ipv6_addr);
243 bool IPAddress::inSubnet(StringPiece cidrNetwork) const {
244 auto subnetInfo = IPAddress::createNetwork(cidrNetwork);
245 return inSubnet(subnetInfo.first, subnetInfo.second);
249 bool IPAddress::inSubnet(const IPAddress& subnet, uint8_t cidr) const {
250 if (bitCount() == subnet.bitCount()) {
252 return asV4().inSubnet(subnet.asV4(), cidr);
254 return asV6().inSubnet(subnet.asV6(), cidr);
257 // an IPv4 address can never belong in a IPv6 subnet unless the IPv6 is a 6to4
258 // address and vice-versa
260 const IPAddressV6& v6addr = asV6();
261 const IPAddressV4& v4subnet = subnet.asV4();
262 if (v6addr.is6To4()) {
263 return v6addr.getIPv4For6To4().inSubnet(v4subnet, cidr);
265 } else if (subnet.isV6()) {
266 const IPAddressV6& v6subnet = subnet.asV6();
267 const IPAddressV4& v4addr = asV4();
268 if (v6subnet.is6To4()) {
269 return v4addr.inSubnet(v6subnet.getIPv4For6To4(), cidr);
276 bool IPAddress::inSubnetWithMask(const IPAddress& subnet,
277 ByteRange mask) const {
278 auto mkByteArray4 = [&]() -> ByteArray4 {
280 std::memcpy(ba.data(), mask.begin(), std::min<size_t>(mask.size(), 4));
284 if (bitCount() == subnet.bitCount()) {
286 return asV4().inSubnetWithMask(subnet.asV4(), mkByteArray4());
289 std::memcpy(ba.data(), mask.begin(), std::min<size_t>(mask.size(), 16));
290 return asV6().inSubnetWithMask(subnet.asV6(), ba);
294 // an IPv4 address can never belong in a IPv6 subnet unless the IPv6 is a 6to4
295 // address and vice-versa
297 const IPAddressV6& v6addr = asV6();
298 const IPAddressV4& v4subnet = subnet.asV4();
299 if (v6addr.is6To4()) {
300 return v6addr.getIPv4For6To4().inSubnetWithMask(v4subnet, mkByteArray4());
302 } else if (subnet.isV6()) {
303 const IPAddressV6& v6subnet = subnet.asV6();
304 const IPAddressV4& v4addr = asV4();
305 if (v6subnet.is6To4()) {
306 return v4addr.inSubnetWithMask(v6subnet.getIPv4For6To4(), mkByteArray4());
312 uint8_t IPAddress::getNthMSByte(size_t byteIndex) const {
313 const auto highestIndex = byteCount() - 1;
314 if (byteIndex > highestIndex) {
315 throw std::invalid_argument(to<string>("Byte index must be <= ",
316 to<string>(highestIndex), " for addresses of type :",
317 detail::familyNameStr(family())));
320 return asV4().bytes()[byteIndex];
322 return asV6().bytes()[byteIndex];
326 bool operator==(const IPAddress& addr1, const IPAddress& addr2) {
327 if (addr1.family() == addr2.family()) {
329 return (addr1.asV6() == addr2.asV6());
330 } else if (addr1.isV4()) {
331 return (addr1.asV4() == addr2.asV4());
333 CHECK_EQ(addr1.family(), AF_UNSPEC);
334 // Two default initialized AF_UNSPEC addresses should be considered equal.
335 // AF_UNSPEC is the only other value for which an IPAddress can be
336 // created, in the default constructor case.
340 // addr1 is v4 mapped v6 address, addr2 is v4
341 if (addr1.isIPv4Mapped() && addr2.isV4()) {
342 if (IPAddress::createIPv4(addr1) == addr2.asV4()) {
346 // addr2 is v4 mapped v6 address, addr1 is v4
347 if (addr2.isIPv4Mapped() && addr1.isV4()) {
348 if (IPAddress::createIPv4(addr2) == addr1.asV4()) {
352 // we only compare IPv4 and IPv6 addresses
356 bool operator<(const IPAddress& addr1, const IPAddress& addr2) {
357 if (addr1.family() == addr2.family()) {
359 return (addr1.asV6() < addr2.asV6());
360 } else if (addr1.isV4()) {
361 return (addr1.asV4() < addr2.asV4());
363 CHECK_EQ(addr1.family(), AF_UNSPEC);
364 // Two default initialized AF_UNSPEC addresses can not be less than each
365 // other. AF_UNSPEC is the only other value for which an IPAddress can be
366 // created, in the default constructor case.
371 // means addr2 is v4, convert it to a mapped v6 address and compare
372 return addr1.asV6() < addr2.asV4().createIPv6();
375 // means addr2 is v6, convert addr1 to v4 mapped and compare
376 return addr1.asV4().createIPv6() < addr2.asV6();
382 IPAddress::longestCommonPrefix(const CIDRNetwork& one, const CIDRNetwork& two) {
383 if (one.first.family() != two.first.family()) {
384 throw std::invalid_argument(to<string>("Can't compute "
385 "longest common prefix between addresses of different families. "
386 "Passed: ", detail::familyNameStr(one.first.family()), " and ",
387 detail::familyNameStr(two.first.family())));
389 if (one.first.isV4()) {
390 auto prefix = IPAddressV4::longestCommonPrefix(
391 {one.first.asV4(), one.second},
392 {two.first.asV4(), two.second});
393 return {IPAddress(prefix.first), prefix.second};
394 } else if (one.first.isV6()) {
395 auto prefix = IPAddressV6::longestCommonPrefix(
396 {one.first.asV6(), one.second},
397 {two.first.asV6(), two.second});
398 return {IPAddress(prefix.first), prefix.second};
400 throw std::invalid_argument("Unknown address family");
402 return {IPAddress(0), 0};