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/IPAddressV4.h>
22 #include <folly/Format.h>
23 #include <folly/IPAddress.h>
24 #include <folly/IPAddressV6.h>
25 #include <folly/detail/IPAddressSource.h>
34 size_t hash_value(const IPAddressV4& addr) {
37 ostream& operator<<(ostream& os, const IPAddressV4& addr) {
41 void toAppend(IPAddressV4 addr, string* result) {
42 result->append(addr.str());
44 void toAppend(IPAddressV4 addr, fbstring* result) {
45 result->append(addr.str());
48 bool IPAddressV4::validate(StringPiece ip) {
49 constexpr size_t kStrMaxLen = INET_ADDRSTRLEN;
50 std::array<char, kStrMaxLen + 1> ip_cstr;
51 const size_t len = std::min(ip.size(), kStrMaxLen);
52 std::memcpy(ip_cstr.data(), ip.data(), len);
55 return 1 == inet_pton(AF_INET, ip_cstr.data(), &addr);
59 IPAddressV4 IPAddressV4::fromLong(uint32_t src) {
62 return IPAddressV4(addr);
65 IPAddressV4 IPAddressV4::fromLongHBO(uint32_t src) {
67 addr.s_addr = htonl(src);
68 return IPAddressV4(addr);
72 uint32_t IPAddressV4::toLong(StringPiece ip) {
75 if (inet_pton(AF_INET, str.c_str(), &addr) != 1) {
76 throw IPAddressFormatException(
77 sformat("Can't convert invalid IP '{}' to long", ip));
83 uint32_t IPAddressV4::toLongHBO(StringPiece ip) {
84 return ntohl(IPAddressV4::toLong(ip));
87 // public default constructor
88 IPAddressV4::IPAddressV4() {
91 // ByteArray4 constructor
92 IPAddressV4::IPAddressV4(const ByteArray4& src)
97 // public string constructor
98 IPAddressV4::IPAddressV4(StringPiece addr)
101 auto ip = addr.str();
102 if (inet_pton(AF_INET, ip.c_str(), &addr_.inAddr_) != 1) {
103 throw IPAddressFormatException(sformat("Invalid IPv4 address '{}'", addr));
107 // in_addr constructor
108 IPAddressV4::IPAddressV4(const in_addr src)
114 void IPAddressV4::setFromBinary(ByteRange bytes) {
115 if (bytes.size() != 4) {
116 throw IPAddressFormatException(sformat(
117 "Invalid IPv4 binary data: length must be 4 bytes, got {}",
120 memcpy(&addr_.inAddr_.s_addr, bytes.data(), sizeof(in_addr));
124 IPAddressV4 IPAddressV4::fromInverseArpaName(const std::string& arpaname) {
125 auto piece = StringPiece(arpaname);
126 // input must be something like 1.0.168.192.in-addr.arpa
127 if (!piece.removeSuffix(".in-addr.arpa")) {
128 throw IPAddressFormatException(
129 sformat("input does not end with '.in-addr.arpa': '{}'", arpaname));
131 std::vector<StringPiece> pieces;
132 split(".", piece, pieces);
133 if (pieces.size() != 4) {
134 throw IPAddressFormatException(sformat("Invalid input. Got {}", piece));
136 // reverse 1.0.168.192 -> 192.168.0.1
137 return IPAddressV4(join(".", pieces.rbegin(), pieces.rend()));
141 IPAddressV6 IPAddressV4::createIPv6() const {
145 std::memcpy(&ba[12], bytes(), 4);
146 return IPAddressV6(ba);
150 IPAddressV6 IPAddressV4::getIPv6For6To4() const {
152 ba[0] = (uint8_t)((IPAddressV6::PREFIX_6TO4 & 0xFF00) >> 8);
153 ba[1] = (uint8_t)(IPAddressV6::PREFIX_6TO4 & 0x00FF);
154 std::memcpy(&ba[2], bytes(), 4);
155 return IPAddressV6(ba);
159 string IPAddressV4::toJson() const {
160 return sformat("{{family:'AF_INET', addr:'{}', hash:{}}}", str(), hash());
164 bool IPAddressV4::inSubnet(StringPiece cidrNetwork) const {
165 auto subnetInfo = IPAddress::createNetwork(cidrNetwork);
166 auto addr = subnetInfo.first;
168 throw IPAddressFormatException(
169 sformat("Address '{}' is not a V4 address", addr.toJson()));
171 return inSubnetWithMask(addr.asV4(), fetchMask(subnetInfo.second));
175 bool IPAddressV4::inSubnetWithMask(const IPAddressV4& subnet,
176 const ByteArray4 cidrMask) const {
177 const ByteArray4 mask = detail::Bytes::mask(toByteArray(), cidrMask);
178 const ByteArray4 subMask = detail::Bytes::mask(subnet.toByteArray(),
180 return (mask == subMask);
184 bool IPAddressV4::isLoopback() const {
185 static IPAddressV4 loopback_addr("127.0.0.0");
186 return inSubnetWithMask(loopback_addr, fetchMask(8));
190 bool IPAddressV4::isLinkLocal() const {
191 static IPAddressV4 linklocal_addr("169.254.0.0");
192 return inSubnetWithMask(linklocal_addr, fetchMask(16));
196 bool IPAddressV4::isNonroutable() const {
197 auto ip = toLongHBO();
198 return isPrivate() ||
199 (ip <= 0x00FFFFFF) || // 0.0.0.0-0.255.255.255
200 (ip >= 0xC0000000 && ip <= 0xC00000FF) || // 192.0.0.0-192.0.0.255
201 (ip >= 0xC0000200 && ip <= 0xC00002FF) || // 192.0.2.0-192.0.2.255
202 (ip >= 0xC6120000 && ip <= 0xC613FFFF) || // 198.18.0.0-198.19.255.255
203 (ip >= 0xC6336400 && ip <= 0xC63364FF) || // 198.51.100.0-198.51.100.255
204 (ip >= 0xCB007100 && ip <= 0xCB0071FF) || // 203.0.113.0-203.0.113.255
205 (ip >= 0xE0000000 && ip <= 0xFFFFFFFF); // 224.0.0.0-255.255.255.255
209 bool IPAddressV4::isPrivate() const {
210 auto ip = toLongHBO();
212 (ip >= 0x0A000000 && ip <= 0x0AFFFFFF) || // 10.0.0.0-10.255.255.255
213 (ip >= 0x7F000000 && ip <= 0x7FFFFFFF) || // 127.0.0.0-127.255.255.255
214 (ip >= 0xA9FE0000 && ip <= 0xA9FEFFFF) || // 169.254.0.0-169.254.255.255
215 (ip >= 0xAC100000 && ip <= 0xAC1FFFFF) || // 172.16.0.0-172.31.255.255
216 (ip >= 0xC0A80000 && ip <= 0xC0A8FFFF); // 192.168.0.0-192.168.255.255
220 bool IPAddressV4::isMulticast() const {
221 return (toLongHBO() & 0xf0000000) == 0xe0000000;
225 IPAddressV4 IPAddressV4::mask(size_t numBits) const {
226 static const auto bits = bitCount();
227 if (numBits > bits) {
228 throw IPAddressFormatException(
229 sformat("numBits({}) > bitsCount({})", numBits, bits));
232 ByteArray4 ba = detail::Bytes::mask(fetchMask(numBits), addr_.bytes_);
233 return IPAddressV4(ba);
237 string IPAddressV4::str() const {
238 return detail::fastIpv4ToString(addr_.inAddr_);
242 void IPAddressV4::toFullyQualifiedAppend(std::string& out) const {
243 detail::fastIpv4AppendToString(addr_.inAddr_, out);
247 string IPAddressV4::toInverseArpaName() const {
249 "{}.{}.{}.{}.in-addr.arpa",
257 uint8_t IPAddressV4::getNthMSByte(size_t byteIndex) const {
258 const auto highestIndex = byteCount() - 1;
259 if (byteIndex > highestIndex) {
260 throw std::invalid_argument(sformat(
261 "Byte index must be <= {} for addresses of type: {}",
263 detail::familyNameStr(AF_INET)));
265 return bytes()[byteIndex];
268 const ByteArray4 IPAddressV4::fetchMask(size_t numBits) {
269 static const size_t bits = bitCount();
270 if (numBits > bits) {
271 throw IPAddressFormatException("IPv4 addresses are 32 bits");
273 auto const val = Endian::big(uint32_t(~uint64_t(0) << (32 - numBits)));
275 std::memcpy(arr.data(), &val, sizeof(val));
279 CIDRNetworkV4 IPAddressV4::longestCommonPrefix(
280 const CIDRNetworkV4& one,
281 const CIDRNetworkV4& two) {
282 auto prefix = detail::Bytes::longestCommonPrefix(
283 one.first.addr_.bytes_, one.second, two.first.addr_.bytes_, two.second);
284 return {IPAddressV4(prefix.first), prefix.second};