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 to<std::string>("Can't convert invalid IP '", ip, "' ", "to long"));
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(
104 to<std::string>("Invalid IPv4 address '", addr, "'"));
108 // in_addr constructor
109 IPAddressV4::IPAddressV4(const in_addr src)
115 void IPAddressV4::setFromBinary(ByteRange bytes) {
116 if (bytes.size() != 4) {
117 throw IPAddressFormatException(to<std::string>(
118 "Invalid IPv4 binary data: length must ",
122 memcpy(&addr_.inAddr_.s_addr, bytes.data(), sizeof(in_addr));
126 IPAddressV4 IPAddressV4::fromInverseArpaName(const std::string& arpaname) {
127 auto piece = StringPiece(arpaname);
128 // input must be something like 1.0.168.192.in-addr.arpa
129 if (!piece.removeSuffix(".in-addr.arpa")) {
130 throw IPAddressFormatException(
131 sformat("input does not end with '.in-addr.arpa': '{}'", arpaname));
133 std::vector<StringPiece> pieces;
134 split(".", piece, pieces);
135 if (pieces.size() != 4) {
136 throw IPAddressFormatException(sformat("Invalid input. Got {}", piece));
138 // reverse 1.0.168.192 -> 192.168.0.1
139 return IPAddressV4(join(".", pieces.rbegin(), pieces.rend()));
143 IPAddressV6 IPAddressV4::createIPv6() const {
147 std::memcpy(&ba[12], bytes(), 4);
148 return IPAddressV6(ba);
152 IPAddressV6 IPAddressV4::getIPv6For6To4() const {
154 ba[0] = (uint8_t)((IPAddressV6::PREFIX_6TO4 & 0xFF00) >> 8);
155 ba[1] = (uint8_t)(IPAddressV6::PREFIX_6TO4 & 0x00FF);
156 std::memcpy(&ba[2], bytes(), 4);
157 return IPAddressV6(ba);
161 string IPAddressV4::toJson() const {
163 "{{family:'AF_INET', addr:'{}', hash:{}}}", str(), hash()).str();
167 bool IPAddressV4::inSubnet(StringPiece cidrNetwork) const {
168 auto subnetInfo = IPAddress::createNetwork(cidrNetwork);
169 auto addr = subnetInfo.first;
171 throw IPAddressFormatException(to<std::string>(
172 "Address '", addr.toJson(), "' ", "is not a V4 address"));
174 return inSubnetWithMask(addr.asV4(), fetchMask(subnetInfo.second));
178 bool IPAddressV4::inSubnetWithMask(const IPAddressV4& subnet,
179 const ByteArray4 cidrMask) const {
180 const ByteArray4 mask = detail::Bytes::mask(toByteArray(), cidrMask);
181 const ByteArray4 subMask = detail::Bytes::mask(subnet.toByteArray(),
183 return (mask == subMask);
187 bool IPAddressV4::isLoopback() const {
188 static IPAddressV4 loopback_addr("127.0.0.0");
189 return inSubnetWithMask(loopback_addr, fetchMask(8));
193 bool IPAddressV4::isLinkLocal() const {
194 static IPAddressV4 linklocal_addr("169.254.0.0");
195 return inSubnetWithMask(linklocal_addr, fetchMask(16));
199 bool IPAddressV4::isNonroutable() const {
200 auto ip = toLongHBO();
201 return isPrivate() ||
202 (ip <= 0x00FFFFFF) || // 0.0.0.0-0.255.255.255
203 (ip >= 0xC0000000 && ip <= 0xC00000FF) || // 192.0.0.0-192.0.0.255
204 (ip >= 0xC0000200 && ip <= 0xC00002FF) || // 192.0.2.0-192.0.2.255
205 (ip >= 0xC6120000 && ip <= 0xC613FFFF) || // 198.18.0.0-198.19.255.255
206 (ip >= 0xC6336400 && ip <= 0xC63364FF) || // 198.51.100.0-198.51.100.255
207 (ip >= 0xCB007100 && ip <= 0xCB0071FF) || // 203.0.113.0-203.0.113.255
208 (ip >= 0xE0000000 && ip <= 0xFFFFFFFF); // 224.0.0.0-255.255.255.255
212 bool IPAddressV4::isPrivate() const {
213 auto ip = toLongHBO();
215 (ip >= 0x0A000000 && ip <= 0x0AFFFFFF) || // 10.0.0.0-10.255.255.255
216 (ip >= 0x7F000000 && ip <= 0x7FFFFFFF) || // 127.0.0.0-127.255.255.255
217 (ip >= 0xA9FE0000 && ip <= 0xA9FEFFFF) || // 169.254.0.0-169.254.255.255
218 (ip >= 0xAC100000 && ip <= 0xAC1FFFFF) || // 172.16.0.0-172.31.255.255
219 (ip >= 0xC0A80000 && ip <= 0xC0A8FFFF); // 192.168.0.0-192.168.255.255
223 bool IPAddressV4::isMulticast() const {
224 return (toLongHBO() & 0xf0000000) == 0xe0000000;
228 IPAddressV4 IPAddressV4::mask(size_t numBits) const {
229 static const auto bits = bitCount();
230 if (numBits > bits) {
231 throw IPAddressFormatException(
232 to<std::string>("numBits(", numBits, ") > bitsCount(", bits, ")"));
235 ByteArray4 ba = detail::Bytes::mask(fetchMask(numBits), addr_.bytes_);
236 return IPAddressV4(ba);
240 string IPAddressV4::str() const {
241 return detail::fastIpv4ToString(addr_.inAddr_);
245 void IPAddressV4::toFullyQualifiedAppend(std::string& out) const {
246 detail::fastIpv4AppendToString(addr_.inAddr_, out);
250 string IPAddressV4::toInverseArpaName() const {
252 "{}.{}.{}.{}.in-addr.arpa",
260 uint8_t IPAddressV4::getNthMSByte(size_t byteIndex) const {
261 const auto highestIndex = byteCount() - 1;
262 if (byteIndex > highestIndex) {
263 throw std::invalid_argument(to<string>("Byte index must be <= ",
264 to<string>(highestIndex), " for addresses of type :",
265 detail::familyNameStr(AF_INET)));
267 return bytes()[byteIndex];
270 const ByteArray4 IPAddressV4::fetchMask(size_t numBits) {
271 static const size_t bits = bitCount();
272 if (numBits > bits) {
273 throw IPAddressFormatException(
274 to<std::string>("IPv4 addresses are 32 bits"));
276 // masks_ is backed by an array so is zero indexed
277 return masks_[numBits];
280 CIDRNetworkV4 IPAddressV4::longestCommonPrefix(
281 const CIDRNetworkV4& one,
282 const CIDRNetworkV4& two) {
283 auto prefix = detail::Bytes::longestCommonPrefix(
284 one.first.addr_.bytes_, one.second, two.first.addr_.bytes_, two.second);
285 return {IPAddressV4(prefix.first), prefix.second};
289 const std::array<ByteArray4, 33> IPAddressV4::masks_ = {{
290 {{0x00, 0x00, 0x00, 0x00}},
291 {{0x80, 0x00, 0x00, 0x00}},
292 {{0xc0, 0x00, 0x00, 0x00}},
293 {{0xe0, 0x00, 0x00, 0x00}},
294 {{0xf0, 0x00, 0x00, 0x00}},
295 {{0xf8, 0x00, 0x00, 0x00}},
296 {{0xfc, 0x00, 0x00, 0x00}},
297 {{0xfe, 0x00, 0x00, 0x00}},
298 {{0xff, 0x00, 0x00, 0x00}},
299 {{0xff, 0x80, 0x00, 0x00}},
300 {{0xff, 0xc0, 0x00, 0x00}},
301 {{0xff, 0xe0, 0x00, 0x00}},
302 {{0xff, 0xf0, 0x00, 0x00}},
303 {{0xff, 0xf8, 0x00, 0x00}},
304 {{0xff, 0xfc, 0x00, 0x00}},
305 {{0xff, 0xfe, 0x00, 0x00}},
306 {{0xff, 0xff, 0x00, 0x00}},
307 {{0xff, 0xff, 0x80, 0x00}},
308 {{0xff, 0xff, 0xc0, 0x00}},
309 {{0xff, 0xff, 0xe0, 0x00}},
310 {{0xff, 0xff, 0xf0, 0x00}},
311 {{0xff, 0xff, 0xf8, 0x00}},
312 {{0xff, 0xff, 0xfc, 0x00}},
313 {{0xff, 0xff, 0xfe, 0x00}},
314 {{0xff, 0xff, 0xff, 0x00}},
315 {{0xff, 0xff, 0xff, 0x80}},
316 {{0xff, 0xff, 0xff, 0xc0}},
317 {{0xff, 0xff, 0xff, 0xe0}},
318 {{0xff, 0xff, 0xff, 0xf0}},
319 {{0xff, 0xff, 0xff, 0xf8}},
320 {{0xff, 0xff, 0xff, 0xfc}},
321 {{0xff, 0xff, 0xff, 0xfe}},
322 {{0xff, 0xff, 0xff, 0xff}}