2 * Copyright 2014 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 "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) {
150 if (inet_pton(AF_INET6, ip.c_str(), &ipAddr) != 1) {
151 throwFormatException("inet_pton failed for V6 address");
153 addr_ = IPAddressV46(IPAddressV6(ipAddr));
155 } else if (ip.find('.') != string::npos) {
157 if (inet_pton(AF_INET, ip.c_str(), &ipAddr) != 1) {
158 throwFormatException("inet_pton failed for V4 address");
160 addr_ = IPAddressV46(IPAddressV4(ipAddr));
163 throwFormatException("invalid address format");
167 // public sockaddr constructor
168 IPAddress::IPAddress(const sockaddr* addr)
172 if (addr == nullptr) {
173 throw IPAddressFormatException("sockaddr == nullptr");
175 family_ = addr->sa_family;
176 switch (addr->sa_family) {
178 const sockaddr_in *v4addr = reinterpret_cast<const sockaddr_in*>(addr);
179 addr_.ipV4Addr = IPAddressV4(v4addr->sin_addr);
183 const sockaddr_in6 *v6addr = reinterpret_cast<const sockaddr_in6*>(addr);
184 addr_.ipV6Addr = IPAddressV6(v6addr->sin6_addr);
188 throw InvalidAddressFamilyException(addr->sa_family);
192 // public ipv4 constructor
193 IPAddress::IPAddress(const IPAddressV4 ipV4Addr)
199 // public ipv4 constructor
200 IPAddress::IPAddress(const in_addr ipV4Addr)
201 : addr_(IPAddressV4(ipV4Addr))
206 // public ipv6 constructor
207 IPAddress::IPAddress(const IPAddressV6& ipV6Addr)
213 // public ipv6 constructor
214 IPAddress::IPAddress(const in6_addr& ipV6Addr)
215 : addr_(IPAddressV6(ipV6Addr))
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,
269 ByteRange mask) const {
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(to<string>("Byte index must be <= ",
308 to<string>(highestIndex), " for addresses of type :",
309 detail::familyNameStr(family())));
312 return asV4().bytes()[byteIndex];
314 return asV6().bytes()[byteIndex];
318 bool operator==(const IPAddress& addr1, const IPAddress& addr2) {
319 if (addr1.family() == addr2.family()) {
321 return (addr1.asV6() == addr2.asV6());
322 } else if (addr1.isV4()) {
323 return (addr1.asV4() == addr2.asV4());
325 CHECK_EQ(addr1.family(), AF_UNSPEC);
326 // Two default initialized AF_UNSPEC addresses should be considered equal.
327 // AF_UNSPEC is the only other value for which an IPAddress can be
328 // created, in the default constructor case.
332 // addr1 is v4 mapped v6 address, addr2 is v4
333 if (addr1.isIPv4Mapped() && addr2.isV4()) {
334 if (IPAddress::createIPv4(addr1) == addr2.asV4()) {
338 // addr2 is v4 mapped v6 address, addr1 is v4
339 if (addr2.isIPv4Mapped() && addr1.isV4()) {
340 if (IPAddress::createIPv4(addr2) == addr1.asV4()) {
344 // we only compare IPv4 and IPv6 addresses
348 bool operator<(const IPAddress& addr1, const IPAddress& addr2) {
349 if (addr1.family() == addr2.family()) {
351 return (addr1.asV6() < addr2.asV6());
352 } else if (addr1.isV4()) {
353 return (addr1.asV4() < addr2.asV4());
355 CHECK_EQ(addr1.family(), AF_UNSPEC);
356 // Two default initialized AF_UNSPEC addresses can not be less than each
357 // other. AF_UNSPEC is the only other value for which an IPAddress can be
358 // created, in the default constructor case.
363 // means addr2 is v4, convert it to a mapped v6 address and compare
364 return addr1.asV6() < addr2.asV4().createIPv6();
367 // means addr2 is v6, convert addr1 to v4 mapped and compare
368 return addr1.asV4().createIPv6() < addr2.asV6();
374 IPAddress::longestCommonPrefix(const CIDRNetwork& one, const CIDRNetwork& two) {
375 if (one.first.family() != two.first.family()) {
376 throw std::invalid_argument(to<string>("Can't compute "
377 "longest common prefix between addresses of different families. "
378 "Passed: ", detail::familyNameStr(one.first.family()), " and ",
379 detail::familyNameStr(two.first.family())));
381 if (one.first.isV4()) {
382 auto prefix = IPAddressV4::longestCommonPrefix(
383 {one.first.asV4(), one.second},
384 {two.first.asV4(), two.second});
385 return {IPAddress(prefix.first), prefix.second};
386 } else if (one.first.isV6()) {
387 auto prefix = IPAddressV6::longestCommonPrefix(
388 {one.first.asV6(), one.second},
389 {two.first.asV6(), two.second});
390 return {IPAddress(prefix.first), prefix.second};
392 throw std::invalid_argument("Unknown address family");
394 return {IPAddress(0), 0};