IPAddressV4.h 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. /*
  2. * Copyright 2014-present Facebook, Inc.
  3. *
  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
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  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.
  15. */
  16. #pragma once
  17. #include <cstring>
  18. #include <array>
  19. #include <functional>
  20. #include <iosfwd>
  21. #include <folly/Expected.h>
  22. #include <folly/FBString.h>
  23. #include <folly/IPAddressException.h>
  24. #include <folly/Range.h>
  25. #include <folly/detail/IPAddress.h>
  26. #include <folly/hash/Hash.h>
  27. namespace folly {
  28. class IPAddress;
  29. class IPAddressV4;
  30. class IPAddressV6;
  31. /**
  32. * Pair of IPAddressV4, netmask
  33. */
  34. typedef std::pair<IPAddressV4, uint8_t> CIDRNetworkV4;
  35. /**
  36. * Specialization for IPv4 addresses
  37. */
  38. typedef std::array<uint8_t, 4> ByteArray4;
  39. /**
  40. * IPv4 variation of IPAddress.
  41. *
  42. * Added methods: toLong, toLongHBO and createIPv6
  43. *
  44. * @note toLong/fromLong deal in network byte order, use toLongHBO/fromLongHBO
  45. * if working in host byte order.
  46. *
  47. * @see IPAddress
  48. */
  49. class IPAddressV4 {
  50. public:
  51. // Max size of std::string returned by toFullyQualified.
  52. static constexpr size_t kMaxToFullyQualifiedSize =
  53. 4 /*words*/ * 3 /*max chars per word*/ + 3 /*separators*/;
  54. // returns true iff the input string can be parsed as an ipv4-address
  55. static bool validate(StringPiece ip) noexcept;
  56. // create an IPAddressV4 instance from a uint32_t (network byte order)
  57. static IPAddressV4 fromLong(uint32_t src);
  58. // same as above but host byte order
  59. static IPAddressV4 fromLongHBO(uint32_t src);
  60. /**
  61. * Create a new IPAddress instance from the provided binary data.
  62. * @throws IPAddressFormatException if the input length is not 4 bytes.
  63. */
  64. static IPAddressV4 fromBinary(ByteRange bytes);
  65. /**
  66. * Non-throwing version of fromBinary().
  67. * On failure returns IPAddressFormatError.
  68. */
  69. static Expected<IPAddressV4, IPAddressFormatError> tryFromBinary(
  70. ByteRange bytes) noexcept;
  71. /**
  72. * Tries to create a new IPAddressV4 instance from provided string and
  73. * returns it on success. Returns IPAddressFormatError on failure.
  74. */
  75. static Expected<IPAddressV4, IPAddressFormatError> tryFromString(
  76. StringPiece str) noexcept;
  77. /**
  78. * Returns the address as a Range.
  79. */
  80. ByteRange toBinary() const {
  81. return ByteRange((const unsigned char*)&addr_.inAddr_.s_addr, 4);
  82. }
  83. /**
  84. * Create a new IPAddress instance from the in-addr.arpa representation.
  85. * @throws IPAddressFormatException if the input is not a valid in-addr.arpa
  86. * representation
  87. */
  88. static IPAddressV4 fromInverseArpaName(const std::string& arpaname);
  89. /**
  90. * Convert a IPv4 address string to a long in network byte order.
  91. * @param [in] ip the address to convert
  92. * @return the long representation of the address
  93. */
  94. static uint32_t toLong(StringPiece ip);
  95. // Same as above, but in host byte order.
  96. // This is slightly slower than toLong.
  97. static uint32_t toLongHBO(StringPiece ip);
  98. /**
  99. * Default constructor for IPAddressV4.
  100. *
  101. * The address value will be 0.0.0.0
  102. */
  103. IPAddressV4();
  104. // Create an IPAddressV4 from a string
  105. // @throws IPAddressFormatException
  106. explicit IPAddressV4(StringPiece ip);
  107. // ByteArray4 constructor
  108. explicit IPAddressV4(const ByteArray4& src) noexcept;
  109. // in_addr constructor
  110. explicit IPAddressV4(const in_addr src) noexcept;
  111. // Return the V6 mapped representation of the address.
  112. IPAddressV6 createIPv6() const;
  113. /**
  114. * Return a V6 address in the format of an 6To4 address.
  115. */
  116. IPAddressV6 getIPv6For6To4() const;
  117. // Return the long (network byte order) representation of the address.
  118. uint32_t toLong() const {
  119. return toAddr().s_addr;
  120. }
  121. // Return the long (host byte order) representation of the address.
  122. // This is slightly slower than toLong.
  123. uint32_t toLongHBO() const {
  124. return ntohl(toLong());
  125. }
  126. /**
  127. * @see IPAddress#bitCount
  128. * @returns 32
  129. */
  130. static constexpr size_t bitCount() {
  131. return 32;
  132. }
  133. /**
  134. * @See IPAddress#toJson
  135. */
  136. std::string toJson() const;
  137. size_t hash() const {
  138. static const uint32_t seed = AF_INET;
  139. uint32_t hashed = hash::fnv32_buf(&addr_, 4);
  140. return hash::hash_combine(seed, hashed);
  141. }
  142. // @see IPAddress#inSubnet
  143. // @throws IPAddressFormatException if string doesn't contain a V4 address
  144. bool inSubnet(StringPiece cidrNetwork) const;
  145. // return true if address is in subnet
  146. bool inSubnet(const IPAddressV4& subnet, uint8_t cidr) const {
  147. return inSubnetWithMask(subnet, fetchMask(cidr));
  148. }
  149. bool inSubnetWithMask(const IPAddressV4& subnet, const ByteArray4 mask) const;
  150. // @see IPAddress#isLoopback
  151. bool isLoopback() const;
  152. // @see IPAddress#isLinkLocal
  153. bool isLinkLocal() const;
  154. // @see IPAddress#isNonroutable
  155. bool isNonroutable() const;
  156. // @see IPAddress#isPrivate
  157. bool isPrivate() const;
  158. // @see IPAddress#isMulticast
  159. bool isMulticast() const;
  160. // @see IPAddress#isZero
  161. bool isZero() const {
  162. constexpr auto zero = ByteArray4{{}};
  163. return 0 == std::memcmp(bytes(), zero.data(), zero.size());
  164. }
  165. bool isLinkLocalBroadcast() const {
  166. return (INADDR_BROADCAST == toLongHBO());
  167. }
  168. // @see IPAddress#mask
  169. IPAddressV4 mask(size_t numBits) const;
  170. // @see IPAddress#str
  171. std::string str() const;
  172. std::string toInverseArpaName() const;
  173. // return underlying in_addr structure
  174. in_addr toAddr() const {
  175. return addr_.inAddr_;
  176. }
  177. sockaddr_in toSockAddr() const {
  178. sockaddr_in addr;
  179. memset(&addr, 0, sizeof(sockaddr_in));
  180. addr.sin_family = AF_INET;
  181. memcpy(&addr.sin_addr, &addr_.inAddr_, sizeof(in_addr));
  182. return addr;
  183. }
  184. ByteArray4 toByteArray() const {
  185. ByteArray4 ba{{0}};
  186. std::memcpy(ba.data(), bytes(), 4);
  187. return ba;
  188. }
  189. // @see IPAddress#toFullyQualified
  190. std::string toFullyQualified() const {
  191. return str();
  192. }
  193. // @see IPAddress#toFullyQualifiedAppend
  194. void toFullyQualifiedAppend(std::string& out) const;
  195. // @see IPAddress#version
  196. uint8_t version() const {
  197. return 4;
  198. }
  199. /**
  200. * Return the mask associated with the given number of bits.
  201. * If for instance numBits was 24 (e.g. /24) then the V4 mask returned should
  202. * be {0xff, 0xff, 0xff, 0x00}.
  203. * @param [in] numBits bitmask to retrieve
  204. * @throws abort if numBits == 0 or numBits > bitCount()
  205. * @return mask associated with numBits
  206. */
  207. static const ByteArray4 fetchMask(size_t numBits);
  208. // Given 2 IPAddressV4, mask pairs extract the longest common IPAddress,
  209. // mask pair
  210. static CIDRNetworkV4 longestCommonPrefix(
  211. const CIDRNetworkV4& one,
  212. const CIDRNetworkV4& two);
  213. // Number of bytes in the address representation.
  214. static size_t byteCount() {
  215. return 4;
  216. }
  217. // get nth most significant bit - 0 indexed
  218. bool getNthMSBit(size_t bitIndex) const {
  219. return detail::getNthMSBitImpl(*this, bitIndex, AF_INET);
  220. }
  221. // get nth most significant byte - 0 indexed
  222. uint8_t getNthMSByte(size_t byteIndex) const;
  223. // get nth bit - 0 indexed
  224. bool getNthLSBit(size_t bitIndex) const {
  225. return getNthMSBit(bitCount() - bitIndex - 1);
  226. }
  227. // get nth byte - 0 indexed
  228. uint8_t getNthLSByte(size_t byteIndex) const {
  229. return getNthMSByte(byteCount() - byteIndex - 1);
  230. }
  231. const unsigned char* bytes() const {
  232. return addr_.bytes_.data();
  233. }
  234. private:
  235. union AddressStorage {
  236. static_assert(
  237. sizeof(in_addr) == sizeof(ByteArray4),
  238. "size of in_addr and ByteArray4 are different");
  239. in_addr inAddr_;
  240. ByteArray4 bytes_;
  241. AddressStorage() {
  242. std::memset(this, 0, sizeof(AddressStorage));
  243. }
  244. explicit AddressStorage(const ByteArray4 bytes) : bytes_(bytes) {}
  245. explicit AddressStorage(const in_addr addr) : inAddr_(addr) {}
  246. } addr_;
  247. /**
  248. * Set the current IPAddressV4 object to have the address specified by bytes.
  249. * Returns IPAddressFormatError if bytes.size() is not 4.
  250. */
  251. Expected<Unit, IPAddressFormatError> trySetFromBinary(
  252. ByteRange bytes) noexcept;
  253. };
  254. // boost::hash uses hash_value() so this allows boost::hash to work
  255. // automatically for IPAddressV4
  256. size_t hash_value(const IPAddressV4& addr);
  257. std::ostream& operator<<(std::ostream& os, const IPAddressV4& addr);
  258. // Define toAppend() to allow IPAddressV4 to be used with to<string>
  259. void toAppend(IPAddressV4 addr, std::string* result);
  260. void toAppend(IPAddressV4 addr, fbstring* result);
  261. /**
  262. * Return true if two addresses are equal.
  263. */
  264. inline bool operator==(const IPAddressV4& addr1, const IPAddressV4& addr2) {
  265. return (addr1.toLong() == addr2.toLong());
  266. }
  267. // Return true if addr1 < addr2
  268. inline bool operator<(const IPAddressV4& addr1, const IPAddressV4& addr2) {
  269. return (addr1.toLongHBO() < addr2.toLongHBO());
  270. }
  271. // Derived operators
  272. inline bool operator!=(const IPAddressV4& a, const IPAddressV4& b) {
  273. return !(a == b);
  274. }
  275. inline bool operator>(const IPAddressV4& a, const IPAddressV4& b) {
  276. return b < a;
  277. }
  278. inline bool operator<=(const IPAddressV4& a, const IPAddressV4& b) {
  279. return !(a > b);
  280. }
  281. inline bool operator>=(const IPAddressV4& a, const IPAddressV4& b) {
  282. return !(a < b);
  283. }
  284. } // namespace folly
  285. namespace std {
  286. template <>
  287. struct hash<folly::IPAddressV4> {
  288. size_t operator()(const folly::IPAddressV4 addr) const {
  289. return addr.hash();
  290. }
  291. };
  292. } // namespace std