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.
25 #include <folly/Hash.h>
26 #include <folly/Range.h>
27 #include <folly/detail/IPAddress.h>
36 * Pair of IPAddressV4, netmask
38 typedef std::pair<IPAddressV4, uint8_t> CIDRNetworkV4;
41 * Specialization for IPv4 addresses
43 typedef std::array<uint8_t, 4> ByteArray4;
46 * IPv4 variation of IPAddress.
48 * Added methods: toLong, toLongHBO and createIPv6
50 * @note toLong/fromLong deal in network byte order, use toLongHBO/fromLongHBO
51 * if working in host byte order.
57 // Max size of std::string returned by toFullyQualified.
58 static constexpr size_t kMaxToFullyQualifiedSize =
59 4 /*words*/ * 3 /*max chars per word*/ + 3 /*separators*/;
61 // returns true iff the input string can be parsed as an ipv4-address
62 static bool validate(StringPiece ip);
64 // create an IPAddressV4 instance from a uint32_t (network byte order)
65 static IPAddressV4 fromLong(uint32_t src);
66 // same as above but host byte order
67 static IPAddressV4 fromLongHBO(uint32_t src);
70 * Create a new IPAddress instance from the provided binary data.
71 * @throws IPAddressFormatException if the input length is not 4 bytes.
73 static IPAddressV4 fromBinary(ByteRange bytes) {
75 addr.setFromBinary(bytes);
80 * Returns the address as a Range.
82 ByteRange toBinary() const {
83 return ByteRange((const unsigned char *) &addr_.inAddr_.s_addr, 4);
87 * Create a new IPAddress instance from the in-addr.arpa representation.
88 * @throws IPAddressFormatException if the input is not a valid in-addr.arpa
91 static IPAddressV4 fromInverseArpaName(const std::string& arpaname);
94 * Convert a IPv4 address string to a long in network byte order.
95 * @param [in] ip the address to convert
96 * @return the long representation of the address
98 static uint32_t toLong(StringPiece ip);
99 // Same as above, but in host byte order.
100 // This is slightly slower than toLong.
101 static uint32_t toLongHBO(StringPiece ip);
104 * Default constructor for IPAddressV4.
106 * The address value will be 0.0.0.0
110 // Create an IPAddressV4 from a string
111 // @throws IPAddressFormatException
112 explicit IPAddressV4(StringPiece ip);
114 // ByteArray4 constructor
115 explicit IPAddressV4(const ByteArray4& src);
117 // in_addr constructor
118 explicit IPAddressV4(const in_addr src);
120 // Return the V6 mapped representation of the address.
121 IPAddressV6 createIPv6() const;
124 * Return a V6 address in the format of an 6To4 address.
126 IPAddressV6 getIPv6For6To4() const;
128 // Return the long (network byte order) representation of the address.
129 uint32_t toLong() const {
130 return toAddr().s_addr;
133 // Return the long (host byte order) representation of the address.
134 // This is slightly slower than toLong.
135 uint32_t toLongHBO() const {
136 return ntohl(toLong());
140 * @see IPAddress#bitCount
143 static size_t bitCount() { return 32; }
146 * @See IPAddress#toJson
148 std::string toJson() const;
150 size_t hash() const {
151 static const uint32_t seed = AF_INET;
152 uint32_t hashed = hash::fnv32_buf(&addr_, 4);
153 return hash::hash_combine(seed, hashed);
156 // @see IPAddress#inSubnet
157 // @throws IPAddressFormatException if string doesn't contain a V4 address
158 bool inSubnet(StringPiece cidrNetwork) const;
160 // return true if address is in subnet
161 bool inSubnet(const IPAddressV4& subnet, uint8_t cidr) const {
162 return inSubnetWithMask(subnet, fetchMask(cidr));
164 bool inSubnetWithMask(const IPAddressV4& subnet, const ByteArray4 mask) const;
166 // @see IPAddress#isLoopback
167 bool isLoopback() const;
169 // @see IPAddress#isLinkLocal
170 bool isLinkLocal() const;
172 // @see IPAddress#isNonroutable
173 bool isNonroutable() const;
175 // @see IPAddress#isPrivate
176 bool isPrivate() const;
178 // @see IPAddress#isMulticast
179 bool isMulticast() const;
181 // @see IPAddress#isZero
182 bool isZero() const {
183 constexpr auto zero = ByteArray4{{}};
184 return 0 == std::memcmp(bytes(), zero.data(), zero.size());
187 bool isLinkLocalBroadcast() const {
188 return (INADDR_BROADCAST == toLongHBO());
191 // @see IPAddress#mask
192 IPAddressV4 mask(size_t numBits) const;
194 // @see IPAddress#str
195 std::string str() const;
197 std::string toInverseArpaName() const;
199 // return underlying in_addr structure
200 in_addr toAddr() const { return addr_.inAddr_; }
202 sockaddr_in toSockAddr() const {
204 memset(&addr, 0, sizeof(sockaddr_in));
205 addr.sin_family = AF_INET;
206 memcpy(&addr.sin_addr, &addr_.inAddr_, sizeof(in_addr));
210 ByteArray4 toByteArray() const {
212 std::memcpy(ba.data(), bytes(), 4);
216 // @see IPAddress#toFullyQualified
217 std::string toFullyQualified() const { return str(); }
219 // @see IPAddress#toFullyQualifiedAppend
220 void toFullyQualifiedAppend(std::string& out) const;
222 // @see IPAddress#version
223 uint8_t version() const { return 4; }
226 * Return the mask associated with the given number of bits.
227 * If for instance numBits was 24 (e.g. /24) then the V4 mask returned should
228 * be {0xff, 0xff, 0xff, 0x00}.
229 * @param [in] numBits bitmask to retrieve
230 * @throws abort if numBits == 0 or numBits > bitCount()
231 * @return mask associated with numBits
233 static const ByteArray4 fetchMask(size_t numBits);
235 // Given 2 IPAddressV4, mask pairs extract the longest common IPAddress,
237 static CIDRNetworkV4 longestCommonPrefix(
238 const CIDRNetworkV4& one,
239 const CIDRNetworkV4& two);
240 // Number of bytes in the address representation.
241 static size_t byteCount() { return 4; }
242 //get nth most significant bit - 0 indexed
243 bool getNthMSBit(size_t bitIndex) const {
244 return detail::getNthMSBitImpl(*this, bitIndex, AF_INET);
246 //get nth most significant byte - 0 indexed
247 uint8_t getNthMSByte(size_t byteIndex) const;
248 //get nth bit - 0 indexed
249 bool getNthLSBit(size_t bitIndex) const {
250 return getNthMSBit(bitCount() - bitIndex - 1);
252 //get nth byte - 0 indexed
253 uint8_t getNthLSByte(size_t byteIndex) const {
254 return getNthMSByte(byteCount() - byteIndex - 1);
257 const unsigned char* bytes() const { return addr_.bytes_.data(); }
260 union AddressStorage {
261 static_assert(sizeof(in_addr) == sizeof(ByteArray4),
262 "size of in_addr and ByteArray4 are different");
266 std::memset(this, 0, sizeof(AddressStorage));
268 explicit AddressStorage(const ByteArray4 bytes): bytes_(bytes) {}
269 explicit AddressStorage(const in_addr addr): inAddr_(addr) {}
273 * Set the current IPAddressV4 object to have the address specified by bytes.
274 * @throws IPAddressFormatException if bytes.size() is not 4.
276 void setFromBinary(ByteRange bytes);
279 // boost::hash uses hash_value() so this allows boost::hash to work
280 // automatically for IPAddressV4
281 size_t hash_value(const IPAddressV4& addr);
282 std::ostream& operator<<(std::ostream& os, const IPAddressV4& addr);
283 // Define toAppend() to allow IPAddressV4 to be used with to<string>
284 void toAppend(IPAddressV4 addr, std::string* result);
285 void toAppend(IPAddressV4 addr, fbstring* result);
288 * Return true if two addresses are equal.
290 inline bool operator==(const IPAddressV4& addr1, const IPAddressV4& addr2) {
291 return (addr1.toLong() == addr2.toLong());
293 // Return true if addr1 < addr2
294 inline bool operator<(const IPAddressV4& addr1, const IPAddressV4& addr2) {
295 return (addr1.toLongHBO() < addr2.toLongHBO());
298 inline bool operator!=(const IPAddressV4& a, const IPAddressV4& b) {
301 inline bool operator>(const IPAddressV4& a, const IPAddressV4& b) {
304 inline bool operator<=(const IPAddressV4& a, const IPAddressV4& b) {
307 inline bool operator>=(const IPAddressV4& a, const IPAddressV4& b) {
315 struct hash<folly::IPAddressV4> {
316 size_t operator()(const folly::IPAddressV4 addr) const {