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/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());
47 bool IPAddress::validate(StringPiece ip) {
48 return IPAddressV4::validate(ip) || IPAddressV6::validate(ip);
52 IPAddressV4 IPAddress::createIPv4(const IPAddress& addr) {
56 return addr.asV6().createIPv4();
61 IPAddressV6 IPAddress::createIPv6(const IPAddress& addr) {
65 return addr.asV4().createIPv6();
70 CIDRNetwork IPAddress::createNetwork(StringPiece ipSlashCidr,
71 int defaultCidr, /* = -1 */
72 bool applyMask /* = true */) {
73 if (defaultCidr > std::numeric_limits<uint8_t>::max()) {
74 throw std::range_error("defaultCidr must be <= UINT8_MAX");
77 split("/", ipSlashCidr, vec);
78 vector<string>::size_type elemCount = vec.size();
80 if (elemCount == 0 || // weird invalid string
81 elemCount > 2) { // invalid string (IP/CIDR/extras)
82 throw IPAddressFormatException("Invalid ipSlashCidr specified. ",
83 "Expected IP/CIDR format, got ",
84 "'", ipSlashCidr, "'");
86 IPAddress subnet(vec.at(0));
87 uint8_t cidr = (defaultCidr > -1) ? defaultCidr : (subnet.isV4() ? 32 : 128);
91 cidr = to<uint8_t>(vec.at(1));
93 throw IPAddressFormatException("Mask value ",
94 "'", vec.at(1), "' not a valid mask");
97 if (cidr > subnet.bitCount()) {
98 throw IPAddressFormatException("CIDR value '", cidr, "' ",
99 "is > network bit count ",
100 "'", subnet.bitCount(), "'");
102 return std::make_pair(applyMask ? subnet.mask(cidr) : subnet, cidr);
106 IPAddress IPAddress::fromBinary(ByteRange bytes) {
107 if (bytes.size() == 4) {
108 return IPAddress(IPAddressV4::fromBinary(bytes));
109 } else if (bytes.size() == 16) {
110 return IPAddress(IPAddressV6::fromBinary(bytes));
112 string hexval = detail::Bytes::toHex(bytes.data(), bytes.size());
113 throw IPAddressFormatException("Invalid address with hex value ",
119 IPAddress IPAddress::fromLong(uint32_t src) {
120 return IPAddress(IPAddressV4::fromLong(src));
122 IPAddress IPAddress::fromLongHBO(uint32_t src) {
123 return IPAddress(IPAddressV4::fromLongHBO(src));
126 // default constructor
127 IPAddress::IPAddress()
133 // public string constructor
134 IPAddress::IPAddress(StringPiece addr)
138 string ip = addr.str(); // inet_pton() needs NUL-terminated string
139 auto throwFormatException = [&](const string& msg) {
140 throw IPAddressFormatException("Invalid IP '", ip, "': ", msg);
144 throwFormatException("address too short");
146 if (ip.front() == '[' && ip.back() == ']') {
147 ip = ip.substr(1, ip.size() - 2);
150 // need to check for V4 address second, since IPv4-mapped IPv6 addresses may
152 if (ip.find(':') != string::npos) {
153 struct addrinfo* result;
154 struct addrinfo hints;
155 memset(&hints, 0, sizeof(hints));
156 hints.ai_family = AF_INET6;
157 hints.ai_socktype = SOCK_STREAM;
158 hints.ai_flags = AI_NUMERICHOST;
159 if (!getaddrinfo(ip.c_str(), nullptr, &hints, &result)) {
160 struct sockaddr_in6* ipAddr = (struct sockaddr_in6*)result->ai_addr;
161 addr_ = IPAddressV46(IPAddressV6(*ipAddr));
163 freeaddrinfo(result);
165 throwFormatException("getsockaddr failed for V6 address");
167 } else if (ip.find('.') != string::npos) {
169 if (inet_pton(AF_INET, ip.c_str(), &ipAddr) != 1) {
170 throwFormatException("inet_pton failed for V4 address");
172 addr_ = IPAddressV46(IPAddressV4(ipAddr));
175 throwFormatException("invalid address format");
179 // public sockaddr constructor
180 IPAddress::IPAddress(const sockaddr* addr)
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)
211 // public ipv4 constructor
212 IPAddress::IPAddress(const in_addr ipV4Addr)
213 : addr_(IPAddressV4(ipV4Addr))
218 // public ipv6 constructor
219 IPAddress::IPAddress(const IPAddressV6& ipV6Addr)
225 // public ipv6 constructor
226 IPAddress::IPAddress(const in6_addr& ipV6Addr)
227 : addr_(IPAddressV6(ipV6Addr))
232 // Assign from V4 address
233 IPAddress& IPAddress::operator=(const IPAddressV4& ipv4_addr) {
234 addr_ = IPAddressV46(ipv4_addr);
239 // Assign from V6 address
240 IPAddress& IPAddress::operator=(const IPAddressV6& ipv6_addr) {
241 addr_ = IPAddressV46(ipv6_addr);
247 bool IPAddress::inSubnet(StringPiece cidrNetwork) const {
248 auto subnetInfo = IPAddress::createNetwork(cidrNetwork);
249 return inSubnet(subnetInfo.first, subnetInfo.second);
253 bool IPAddress::inSubnet(const IPAddress& subnet, uint8_t cidr) const {
254 if (bitCount() == subnet.bitCount()) {
256 return asV4().inSubnet(subnet.asV4(), cidr);
258 return asV6().inSubnet(subnet.asV6(), cidr);
261 // an IPv4 address can never belong in a IPv6 subnet unless the IPv6 is a 6to4
262 // address and vice-versa
264 const IPAddressV6& v6addr = asV6();
265 const IPAddressV4& v4subnet = subnet.asV4();
266 if (v6addr.is6To4()) {
267 return v6addr.getIPv4For6To4().inSubnet(v4subnet, cidr);
269 } else if (subnet.isV6()) {
270 const IPAddressV6& v6subnet = subnet.asV6();
271 const IPAddressV4& v4addr = asV4();
272 if (v6subnet.is6To4()) {
273 return v4addr.inSubnet(v6subnet.getIPv4For6To4(), cidr);
280 bool IPAddress::inSubnetWithMask(const IPAddress& subnet,
281 ByteRange mask) const {
282 auto mkByteArray4 = [&]() -> ByteArray4 {
284 std::memcpy(ba.data(), mask.begin(), std::min<size_t>(mask.size(), 4));
288 if (bitCount() == subnet.bitCount()) {
290 return asV4().inSubnetWithMask(subnet.asV4(), mkByteArray4());
293 std::memcpy(ba.data(), mask.begin(), std::min<size_t>(mask.size(), 16));
294 return asV6().inSubnetWithMask(subnet.asV6(), ba);
298 // an IPv4 address can never belong in a IPv6 subnet unless the IPv6 is a 6to4
299 // address and vice-versa
301 const IPAddressV6& v6addr = asV6();
302 const IPAddressV4& v4subnet = subnet.asV4();
303 if (v6addr.is6To4()) {
304 return v6addr.getIPv4For6To4().inSubnetWithMask(v4subnet, mkByteArray4());
306 } else if (subnet.isV6()) {
307 const IPAddressV6& v6subnet = subnet.asV6();
308 const IPAddressV4& v4addr = asV4();
309 if (v6subnet.is6To4()) {
310 return v4addr.inSubnetWithMask(v6subnet.getIPv4For6To4(), mkByteArray4());
316 uint8_t IPAddress::getNthMSByte(size_t byteIndex) const {
317 const auto highestIndex = byteCount() - 1;
318 if (byteIndex > highestIndex) {
319 throw std::invalid_argument(to<string>("Byte index must be <= ",
320 to<string>(highestIndex), " for addresses of type :",
321 detail::familyNameStr(family())));
324 return asV4().bytes()[byteIndex];
326 return asV6().bytes()[byteIndex];
330 bool operator==(const IPAddress& addr1, const IPAddress& addr2) {
331 if (addr1.family() == addr2.family()) {
333 return (addr1.asV6() == addr2.asV6());
334 } else if (addr1.isV4()) {
335 return (addr1.asV4() == addr2.asV4());
337 CHECK_EQ(addr1.family(), AF_UNSPEC);
338 // Two default initialized AF_UNSPEC addresses should be considered equal.
339 // AF_UNSPEC is the only other value for which an IPAddress can be
340 // created, in the default constructor case.
344 // addr1 is v4 mapped v6 address, addr2 is v4
345 if (addr1.isIPv4Mapped() && addr2.isV4()) {
346 if (IPAddress::createIPv4(addr1) == addr2.asV4()) {
350 // addr2 is v4 mapped v6 address, addr1 is v4
351 if (addr2.isIPv4Mapped() && addr1.isV4()) {
352 if (IPAddress::createIPv4(addr2) == addr1.asV4()) {
356 // we only compare IPv4 and IPv6 addresses
360 bool operator<(const IPAddress& addr1, const IPAddress& addr2) {
361 if (addr1.family() == addr2.family()) {
363 return (addr1.asV6() < addr2.asV6());
364 } else if (addr1.isV4()) {
365 return (addr1.asV4() < addr2.asV4());
367 CHECK_EQ(addr1.family(), AF_UNSPEC);
368 // Two default initialized AF_UNSPEC addresses can not be less than each
369 // other. AF_UNSPEC is the only other value for which an IPAddress can be
370 // created, in the default constructor case.
375 // means addr2 is v4, convert it to a mapped v6 address and compare
376 return addr1.asV6() < addr2.asV4().createIPv6();
379 // means addr2 is v6, convert addr1 to v4 mapped and compare
380 return addr1.asV4().createIPv6() < addr2.asV6();
386 IPAddress::longestCommonPrefix(const CIDRNetwork& one, const CIDRNetwork& two) {
387 if (one.first.family() != two.first.family()) {
388 throw std::invalid_argument(to<string>("Can't compute "
389 "longest common prefix between addresses of different families. "
390 "Passed: ", detail::familyNameStr(one.first.family()), " and ",
391 detail::familyNameStr(two.first.family())));
393 if (one.first.isV4()) {
394 auto prefix = IPAddressV4::longestCommonPrefix(
395 {one.first.asV4(), one.second},
396 {two.first.asV4(), two.second});
397 return {IPAddress(prefix.first), prefix.second};
398 } else if (one.first.isV6()) {
399 auto prefix = IPAddressV6::longestCommonPrefix(
400 {one.first.asV6(), one.second},
401 {two.first.asV6(), two.second});
402 return {IPAddress(prefix.first), prefix.second};
404 throw std::invalid_argument("Unknown address family");
406 return {IPAddress(0), 0};