proxygen
folly::IPAddressV6 Class Reference

#include <IPAddressV6.h>

Classes

union  AddressStorage
 

Public Types

enum  Type { TEREDO, T6TO4, NORMAL }
 
enum  LinkLocalTag { LINK_LOCAL }
 
typedef std::runtime_error TypeError
 

Public Member Functions

ByteRange toBinary () const
 
 IPAddressV6 ()
 
 IPAddressV6 (StringPiece ip)
 
 IPAddressV6 (const ByteArray16 &src) noexcept
 
 IPAddressV6 (const in6_addr &src) noexcept
 
 IPAddressV6 (const sockaddr_in6 &src) noexcept
 
 IPAddressV6 (LinkLocalTag tag, MacAddress mac)
 
IPAddressV4 createIPv4 () const
 
IPAddressV4 getIPv4For6To4 () const
 
bool is6To4 () const
 
bool isTeredo () const
 
bool isIPv4Mapped () const
 
Type type () const
 
std::string toJson () const
 
size_t hash () const
 
bool inSubnet (StringPiece cidrNetwork) const
 
bool inSubnet (const IPAddressV6 &subnet, uint8_t cidr) const
 
bool inSubnetWithMask (const IPAddressV6 &subnet, const ByteArray16 &mask) const
 
bool isLoopback () const
 
bool isNonroutable () const
 
bool isRoutable () const
 
bool isPrivate () const
 
bool isLinkLocal () const
 
Optional< MacAddressgetMacAddressFromLinkLocal () const
 
Optional< MacAddressgetMacAddressFromEUI64 () const
 
bool isMulticast () const
 
uint8_t getMulticastFlags () const
 
uint8_t getMulticastScope () const
 
bool isZero () const
 
bool isLinkLocalBroadcast () const
 
IPAddressV6 mask (size_t numBits) const
 
in6_addr toAddr () const
 
uint16_t getScopeId () const
 
void setScopeId (uint16_t scope)
 
sockaddr_in6 toSockAddr () const
 
ByteArray16 toByteArray () const
 
std::string toFullyQualified () const
 
void toFullyQualifiedAppend (std::string &out) const
 
std::string toInverseArpaName () const
 
std::string str () const
 
uint8_t version () const
 
IPAddressV6 getSolicitedNodeAddress () const
 
bool getNthMSBit (size_t bitIndex) const
 
uint8_t getNthMSByte (size_t byteIndex) const
 
bool getNthLSBit (size_t bitIndex) const
 
uint8_t getNthLSByte (size_t byteIndex) const
 
const unsigned char * bytes () const
 

Static Public Member Functions

static bool validate (StringPiece ip) noexcept
 
static IPAddressV6 fromBinary (ByteRange bytes)
 
static Expected< IPAddressV6, IPAddressFormatErrortryFromBinary (ByteRange bytes) noexcept
 
static Expected< IPAddressV6, IPAddressFormatErrortryFromString (StringPiece str) noexcept
 
static IPAddressV6 fromInverseArpaName (const std::string &arpaname)
 
static constexpr size_t bitCount ()
 
static const ByteArray16 fetchMask (size_t numBits)
 
static CIDRNetworkV6 longestCommonPrefix (const CIDRNetworkV6 &one, const CIDRNetworkV6 &two)
 
static constexpr size_t byteCount ()
 

Static Public Attributes

static const uint32_t PREFIX_TEREDO = 0x20010000
 
static const uint32_t PREFIX_6TO4 = 0x2002
 
static constexpr size_t kToFullyQualifiedSize
 

Protected Member Functions

bool inBinarySubnet (const std::array< uint8_t, 2 > addr, size_t numBits) const
 

Private Member Functions

auto tie () const
 
Expected< Unit, IPAddressFormatErrortrySetFromBinary (ByteRange bytes) noexcept
 

Private Attributes

union folly::IPAddressV6::AddressStorage addr_
 
uint16_t scope_ {0}
 

Friends

bool operator== (const IPAddressV6 &a, const IPAddressV6 &b)
 
bool operator!= (const IPAddressV6 &a, const IPAddressV6 &b)
 
bool operator< (const IPAddressV6 &a, const IPAddressV6 &b)
 
bool operator> (const IPAddressV6 &a, const IPAddressV6 &b)
 
bool operator<= (const IPAddressV6 &a, const IPAddressV6 &b)
 
bool operator>= (const IPAddressV6 &a, const IPAddressV6 &b)
 

Detailed Description

IPv6 variation of IPAddress.

Added methods: createIPv4, getIPv4For6To4, is6To4, isTeredo, isIPv4Mapped, tryCreateIPv4, type

See also
IPAddress

Notes on scope ID parsing:

getaddrinfo() uses if_nametoindex() to convert interface names into a numerical index. For instance, "fe80::202:c9ff:fec1:ee08%eth0" may return scope ID 2 on some hosts, but other numbers on other hosts. It will fail entirely on hosts without an eth0 interface.

Serializing / Deserializing IPAddressB6's on different hosts that use link-local scoping probably won't work.

Definition at line 71 of file IPAddressV6.h.

Member Typedef Documentation

typedef std::runtime_error folly::IPAddressV6::TypeError

Definition at line 85 of file IPAddressV6.h.

Member Enumeration Documentation

Enumerator
LINK_LOCAL 

Definition at line 81 of file IPAddressV6.h.

Enumerator
TEREDO 
T6TO4 
NORMAL 

Definition at line 74 of file IPAddressV6.h.

Constructor & Destructor Documentation

folly::IPAddressV6::IPAddressV6 ( )

Default constructor for IPAddressV6.

The address value will be ::0

Definition at line 70 of file IPAddressV6.cpp.

Referenced by fromInverseArpaName(), longestCommonPrefix(), mask(), toBinary(), and tryFromString().

70 {}
folly::IPAddressV6::IPAddressV6 ( StringPiece  ip)
explicit

Definition at line 73 of file IPAddressV6.cpp.

References folly::gen::move, and tryFromString().

73  {
74  auto maybeIp = tryFromString(addr);
75  if (maybeIp.hasError()) {
76  throw IPAddressFormatException(
77  to<std::string>("Invalid IPv6 address '", addr, "'"));
78  }
79  *this = std::move(maybeIp.value());
80 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
static Expected< IPAddressV6, IPAddressFormatError > tryFromString(StringPiece str) noexcept
Definition: IPAddressV6.cpp:82
ThreadPoolListHook * addr
folly::IPAddressV6::IPAddressV6 ( const ByteArray16 src)
explicitnoexcept

Definition at line 119 of file IPAddressV6.cpp.

119 : addr_(src) {}
union folly::IPAddressV6::AddressStorage addr_
folly::IPAddressV6::IPAddressV6 ( const in6_addr &  src)
explicitnoexcept

Definition at line 112 of file IPAddressV6.cpp.

112 : addr_(src) {}
union folly::IPAddressV6::AddressStorage addr_
folly::IPAddressV6::IPAddressV6 ( const sockaddr_in6 &  src)
explicitnoexcept

Definition at line 115 of file IPAddressV6.cpp.

116  : addr_(src.sin6_addr), scope_(uint16_t(src.sin6_scope_id)) {}
union folly::IPAddressV6::AddressStorage addr_
folly::IPAddressV6::IPAddressV6 ( LinkLocalTag  tag,
MacAddress  mac 
)

Create a link-local IPAddressV6 from the specified ethernet MAC address.

Definition at line 122 of file IPAddressV6.cpp.

122 : addr_(mac) {}
union folly::IPAddressV6::AddressStorage addr_

Member Function Documentation

static constexpr size_t folly::IPAddressV6::bitCount ( )
inlinestatic
See also
IPAddress::bitCount
Returns
128

Definition at line 189 of file IPAddressV6.h.

References hash(), inSubnet(), string, and toJson().

Referenced by fetchMask(), getNthLSBit(), mask(), and TEST().

189  {
190  return 128;
191  }
static constexpr size_t folly::IPAddressV6::byteCount ( )
inlinestatic

Definition at line 348 of file IPAddressV6.h.

Referenced by getNthLSByte(), and getNthMSByte().

348  {
349  return 16;
350  }
const unsigned char* folly::IPAddressV6::bytes ( ) const
inline
IPAddressV4 folly::IPAddressV6::createIPv4 ( ) const

Definition at line 227 of file IPAddressV6.cpp.

References bytes(), isIPv4Mapped(), and folly::detail::Bytes::mkAddress4().

Referenced by isLoopback(), isPrivate(), and toBinary().

227  {
228  if (!isIPv4Mapped()) {
229  throw IPAddressFormatException("addr is not v4-to-v6-mapped");
230  }
231  const unsigned char* by = bytes();
232  return IPAddressV4(detail::Bytes::mkAddress4(&by[12]));
233 }
const unsigned char * bytes() const
Definition: IPAddressV6.h:367
static in_addr mkAddress4(const uint8_t *src)
bool isIPv4Mapped() const
const ByteArray16 folly::IPAddressV6::fetchMask ( size_t  numBits)
static

Return the mask associated with the given number of bits. If for instance numBits was 24 (e.g. /24) then the V4 mask returned should be {0xff, 0xff, 0xff, 0x00}.

Parameters
[in]numBitsbitmask to retrieve
Exceptions
abortif numBits == 0 or numBits > bitCount()
Returns
mask associated with numBits

Definition at line 501 of file IPAddressV6.cpp.

References folly::Endian::big(), bitCount(), and uint64_t.

Referenced by inSubnet(), mask(), TEST(), and version().

501  {
502  static const size_t bits = bitCount();
503  if (numBits > bits) {
504  throw IPAddressFormatException("IPv6 addresses are 128 bits.");
505  }
506  if (numBits == 0) {
507  return {{0}};
508  }
509  constexpr auto _0s = uint64_t(0);
510  constexpr auto _1s = ~_0s;
511  auto const fragment = Endian::big(_1s << ((128 - numBits) % 64));
512  auto const hi = numBits <= 64 ? fragment : _1s;
513  auto const lo = numBits <= 64 ? _0s : fragment;
514  uint64_t const parts[] = {hi, lo};
515  ByteArray16 arr;
516  std::memcpy(arr.data(), parts, sizeof(parts));
517  return arr;
518 }
static constexpr size_t bitCount()
Definition: IPAddressV6.h:189
static T big(T x)
Definition: Bits.h:259
std::array< uint8_t, 16 > ByteArray16
Definition: IPAddressV6.h:50
IPAddressV6 folly::IPAddressV6::fromBinary ( ByteRange  bytes)
static

Create a new IPAddress instance from the provided binary data.

Exceptions
IPAddressFormatExceptionif the input length is not 16 bytes.

Definition at line 168 of file IPAddressV6.cpp.

References folly::Range< Iter >::size(), and tryFromBinary().

Referenced by getSolicitedNodeAddress(), TEST(), TEST_P(), and folly::toAppend().

168  {
169  auto maybeIp = tryFromBinary(bytes);
170  if (maybeIp.hasError()) {
171  throw IPAddressFormatException(to<std::string>(
172  "Invalid IPv6 binary data: length must be 16 bytes, got ",
173  bytes.size()));
174  }
175  return maybeIp.value();
176 }
const unsigned char * bytes() const
Definition: IPAddressV6.h:367
static Expected< IPAddressV6, IPAddressFormatError > tryFromBinary(ByteRange bytes) noexcept
IPAddressV6 folly::IPAddressV6::fromInverseArpaName ( const std::string arpaname)
static

Create a new IPAddress instance from the ip6.arpa representation.

Exceptions
IPAddressFormatExceptionif the input is not a valid ip6.arpa representation

Definition at line 199 of file IPAddressV6.cpp.

References count, i, IPAddressV6(), folly::range(), folly::sformat(), and folly::split().

Referenced by TEST().

199  {
200  auto piece = StringPiece(arpaname);
201  if (!piece.removeSuffix(".ip6.arpa")) {
202  throw IPAddressFormatException(sformat(
203  "Invalid input. Should end with 'ip6.arpa'. Got '{}'", arpaname));
204  }
205  std::vector<StringPiece> pieces;
206  split(".", piece, pieces);
207  if (pieces.size() != 32) {
208  throw IPAddressFormatException(sformat("Invalid input. Got '{}'", piece));
209  }
210  std::array<char, IPAddressV6::kToFullyQualifiedSize> ip;
211  size_t pos = 0;
212  int count = 0;
213  for (size_t i = 1; i <= pieces.size(); i++) {
214  ip[pos] = pieces[pieces.size() - i][0];
215  pos++;
216  count++;
217  // add ':' every 4 chars
218  if (count == 4 && pos < ip.size()) {
219  ip[pos++] = ':';
220  count = 0;
221  }
222  }
223  return IPAddressV6(folly::range(ip));
224 }
std::string sformat(StringPiece fmt, Args &&...args)
Definition: Format.h:280
void split(const Delim &delimiter, const String &input, std::vector< OutputType > &out, bool ignoreEmpty)
Definition: String-inl.h:382
constexpr Range< Iter > range(Iter first, Iter last)
Definition: Range.h:1114
int * count
Range< const char * > StringPiece
IPAddressV4 folly::IPAddressV6::getIPv4For6To4 ( ) const

Return a V4 address if this is a 6To4 address.

Exceptions
TypeErrorif not a 6To4 address

Definition at line 252 of file IPAddressV6.cpp.

References addr, bytes(), is6To4(), folly::sformat(), str(), uint16_t, uint8_t, and folly::unpackInto().

Referenced by folly::toAppend(), and toBinary().

252  {
253  if (!is6To4()) {
255  sformat("Invalid IP '{}': not a 6to4 address", str()));
256  }
257  // convert 16x8 bytes into first 4x16 bytes
258  uint16_t ints[4] = {0, 0, 0, 0};
259  unpackInto(bytes(), ints, 4);
260  // repack into 4x8
261  union {
262  unsigned char bytes[4];
263  in_addr addr;
264  } ipv4;
265  ipv4.bytes[0] = (uint8_t)((ints[1] & 0xFF00) >> 8);
266  ipv4.bytes[1] = (uint8_t)(ints[1] & 0x00FF);
267  ipv4.bytes[2] = (uint8_t)((ints[2] & 0xFF00) >> 8);
268  ipv4.bytes[3] = (uint8_t)(ints[2] & 0x00FF);
269  return IPAddressV4(ipv4.addr);
270 }
const unsigned char * bytes() const
Definition: IPAddressV6.h:367
std::string sformat(StringPiece fmt, Args &&...args)
Definition: Format.h:280
static void unpackInto(const unsigned char *src, uint16_t *dest, size_t count)
std::string str() const
std::runtime_error TypeError
Definition: IPAddressV6.h:85
ThreadPoolListHook * addr
bool is6To4() const
Definition: IPAddressV6.h:170
Optional< MacAddress > folly::IPAddressV6::getMacAddressFromEUI64 ( ) const

Return the mac address if this is an auto-configured IPv6 address based on EUI-64

Returns
an Optional<MacAddress> union representing the mac address. If the address is not based on EUI-64 it will return an empty Optional. You can use Optional::value() to check whether the mac address is not null.

Definition at line 147 of file IPAddressV6.cpp.

References addr_, bytes(), folly::IPAddressV6::AddressStorage::bytes_, folly::MacAddress::fromBinary(), folly::none, and folly::range().

Referenced by getMacAddressFromLinkLocal(), isNonroutable(), and TEST().

147  {
148  if (!(addr_.bytes_[11] == 0xff && addr_.bytes_[12] == 0xfe)) {
149  return folly::none;
150  }
151  // The auto configured address uses modified EUI-64 format,
152  // See RFC 4291 sections 2.5.1, 2.5.6, and Appendix A
153  std::array<uint8_t, MacAddress::SIZE> bytes;
154  // Step 1: first 8 bytes are network prefix, and can be stripped
155  // Step 2: invert the universal/local (U/L) flag (bit 7)
156  bytes[0] = addr_.bytes_[8] ^ 0x02;
157  // Step 3: copy these bytes as they are
158  bytes[1] = addr_.bytes_[9];
159  bytes[2] = addr_.bytes_[10];
160  // Step 4: strip bytes (0xfffe), which are bytes_[11] and bytes_[12]
161  // Step 5: copy the rest.
162  bytes[3] = addr_.bytes_[13];
163  bytes[4] = addr_.bytes_[14];
164  bytes[5] = addr_.bytes_[15];
165  return Optional<MacAddress>(MacAddress::fromBinary(range(bytes)));
166 }
const unsigned char * bytes() const
Definition: IPAddressV6.h:367
constexpr Range< Iter > range(Iter first, Iter last)
Definition: Range.h:1114
static MacAddress fromBinary(ByteRange value)
Definition: MacAddress.h:55
union folly::IPAddressV6::AddressStorage addr_
constexpr None none
Definition: Optional.h:87
Optional< MacAddress > folly::IPAddressV6::getMacAddressFromLinkLocal ( ) const

Return the mac address if this is a link-local IPv6 address.

Returns
an Optional<MacAddress> union representing the mac address.

If the address is not a link-local one it will return an empty Optional. You can use Optional::value() to check whether the mac address is not null.

Definition at line 139 of file IPAddressV6.cpp.

References getMacAddressFromEUI64(), isLinkLocal(), and folly::none.

Referenced by isNonroutable(), and TEST().

139  {
140  // Returned MacAddress must be constructed from a link-local IPv6 address.
141  if (!isLinkLocal()) {
142  return folly::none;
143  }
144  return getMacAddressFromEUI64();
145 }
bool isLinkLocal() const
Optional< MacAddress > getMacAddressFromEUI64() const
constexpr None none
Definition: Optional.h:87
uint8_t folly::IPAddressV6::getMulticastFlags ( ) const

Return the flags for a multicast address. This method may only be called on multicast addresses.

Definition at line 390 of file IPAddressV6.cpp.

References addr_, folly::IPAddressV6::AddressStorage::bytes_, isMulticast(), and uint8_t.

Referenced by isNonroutable().

390  {
391  DCHECK(isMulticast());
392  return uint8_t((addr_.bytes_[1] >> 4) & 0xf);
393 }
bool isMulticast() const
union folly::IPAddressV6::AddressStorage addr_
uint8_t folly::IPAddressV6::getMulticastScope ( ) const

Return the scope for a multicast address. This method may only be called on multicast addresses.

Definition at line 395 of file IPAddressV6.cpp.

References addr_, folly::IPAddressV6::AddressStorage::bytes_, isMulticast(), and uint8_t.

Referenced by isNonroutable(), and isRoutable().

395  {
396  DCHECK(isMulticast());
397  return uint8_t(addr_.bytes_[1] & 0xf);
398 }
bool isMulticast() const
union folly::IPAddressV6::AddressStorage addr_
bool folly::IPAddressV6::getNthLSBit ( size_t  bitIndex) const
inline

Definition at line 359 of file IPAddressV6.h.

References bitCount(), and getNthMSBit().

359  {
360  return getNthMSBit(bitCount() - bitIndex - 1);
361  }
static constexpr size_t bitCount()
Definition: IPAddressV6.h:189
bool getNthMSBit(size_t bitIndex) const
Definition: IPAddressV6.h:353
uint8_t folly::IPAddressV6::getNthLSByte ( size_t  byteIndex) const
inline

Definition at line 363 of file IPAddressV6.h.

References byteCount(), and getNthMSByte().

363  {
364  return getNthMSByte(byteCount() - byteIndex - 1);
365  }
uint8_t getNthMSByte(size_t byteIndex) const
static constexpr size_t byteCount()
Definition: IPAddressV6.h:348
bool folly::IPAddressV6::getNthMSBit ( size_t  bitIndex) const
inline

Definition at line 353 of file IPAddressV6.h.

References folly::detail::getNthMSBitImpl(), getNthMSByte(), and uint8_t.

Referenced by getNthLSBit().

353  {
354  return detail::getNthMSBitImpl(*this, bitIndex, AF_INET6);
355  }
bool getNthMSBitImpl(const IPAddrType &ip, size_t bitIndex, sa_family_t family)
Definition: IPAddress.h:49
uint8_t folly::IPAddressV6::getNthMSByte ( size_t  byteIndex) const

Definition at line 489 of file IPAddressV6.cpp.

References byteCount(), bytes(), folly::detail::familyNameStr(), and folly::sformat().

Referenced by getNthLSByte(), and getNthMSBit().

489  {
490  const auto highestIndex = byteCount() - 1;
491  if (byteIndex > highestIndex) {
492  throw std::invalid_argument(sformat(
493  "Byte index must be <= {} for addresses of type: {}",
494  highestIndex,
495  detail::familyNameStr(AF_INET6)));
496  }
497  return bytes()[byteIndex];
498 }
const unsigned char * bytes() const
Definition: IPAddressV6.h:367
std::string sformat(StringPiece fmt, Args &&...args)
Definition: Format.h:280
static constexpr size_t byteCount()
Definition: IPAddressV6.h:348
std::string familyNameStr(sa_family_t family)
Definition: IPAddress.h:30
uint16_t folly::IPAddressV6::getScopeId ( ) const
inline

Definition at line 290 of file IPAddressV6.h.

References scope_.

Referenced by str().

290  {
291  return scope_;
292  }
IPAddressV6 folly::IPAddressV6::getSolicitedNodeAddress ( ) const

Return the solicited-node multicast address for this address.

Definition at line 400 of file IPAddressV6.cpp.

References addr_, bytes(), folly::IPAddressV6::AddressStorage::bytes_, fromBinary(), isMulticast(), and uint8_t.

Referenced by version().

400  {
401  // Solicted node addresses must be constructed from unicast (or anycast)
402  // addresses
403  DCHECK(!isMulticast());
404 
405  uint8_t bytes[16] = {
406  0xff,
407  0x02,
408  0x00,
409  0x00,
410  0x00,
411  0x00,
412  0x00,
413  0x00,
414  0x00,
415  0x00,
416  0x00,
417  0x01,
418  0xff,
419  addr_.bytes_[13],
420  addr_.bytes_[14],
421  addr_.bytes_[15],
422  };
423  return IPAddressV6::fromBinary(ByteRange(bytes, 16));
424 }
const unsigned char * bytes() const
Definition: IPAddressV6.h:367
static IPAddressV6 fromBinary(ByteRange bytes)
bool isMulticast() const
Range< const unsigned char * > ByteRange
Definition: Range.h:1163
union folly::IPAddressV6::AddressStorage addr_
size_t folly::IPAddressV6::hash ( ) const

Definition at line 314 of file IPAddressV6.cpp.

References addr_, folly::hash::SpookyHashV2::Hash128(), folly::hash::hash_combine(), isIPv4Mapped(), seed, and uint64_t.

Referenced by bitCount(), folly::hash_value(), std::hash< folly::IPAddressV6 >::operator()(), and toJson().

314  {
315  if (isIPv4Mapped()) {
316  /* An IPAddress containing this object would be equal (i.e. operator==)
317  to an IPAddress containing the corresponding IPv4.
318  So we must make sure that the hash values are the same as well */
319  return IPAddress::createIPv4(*this).hash();
320  }
321 
322  static const uint64_t seed = AF_INET6;
323  uint64_t hash1 = 0, hash2 = 0;
324  hash::SpookyHashV2::Hash128(&addr_, 16, &hash1, &hash2);
325  return hash::hash_combine(seed, hash1, hash2);
326 }
static const int seed
static void Hash128(const void *message, size_t length, uint64_t *hash1, uint64_t *hash2)
size_t hash_combine(const T &t, const Ts &...ts) noexcept(noexcept(hash_combine_generic(StdHasher{}, t, ts...)))
Definition: Hash.h:669
union folly::IPAddressV6::AddressStorage addr_
bool isIPv4Mapped() const
bool folly::IPAddressV6::inBinarySubnet ( const std::array< uint8_t, 2 >  addr,
size_t  numBits 
) const
protected

Helper that returns true if the address is in the binary subnet specified by addr.

Definition at line 530 of file IPAddressV6.cpp.

References mask().

Referenced by bytes(), isLinkLocal(), isPrivate(), and isRoutable().

532  {
533  auto masked = mask(numBits);
534  return (std::memcmp(addr.data(), masked.bytes(), 2) == 0);
535 }
IPAddressV6 mask(size_t numBits) const
bool folly::IPAddressV6::inSubnet ( StringPiece  cidrNetwork) const

Definition at line 329 of file IPAddressV6.cpp.

References addr, fetchMask(), inSubnetWithMask(), and folly::sformat().

Referenced by bitCount().

329  {
330  auto subnetInfo = IPAddress::createNetwork(cidrNetwork);
331  auto addr = subnetInfo.first;
332  if (!addr.isV6()) {
333  throw IPAddressFormatException(
334  sformat("Address '{}' is not a V6 address", addr.toJson()));
335  }
336  return inSubnetWithMask(addr.asV6(), fetchMask(subnetInfo.second));
337 }
bool inSubnetWithMask(const IPAddressV6 &subnet, const ByteArray16 &mask) const
std::string sformat(StringPiece fmt, Args &&...args)
Definition: Format.h:280
static const ByteArray16 fetchMask(size_t numBits)
ThreadPoolListHook * addr
bool folly::IPAddressV6::inSubnet ( const IPAddressV6 subnet,
uint8_t  cidr 
) const
inline

Definition at line 205 of file IPAddressV6.h.

References fetchMask(), inSubnetWithMask(), isLoopback(), and mask().

205  {
206  return inSubnetWithMask(subnet, fetchMask(cidr));
207  }
bool inSubnetWithMask(const IPAddressV6 &subnet, const ByteArray16 &mask) const
static const ByteArray16 fetchMask(size_t numBits)
bool folly::IPAddressV6::inSubnetWithMask ( const IPAddressV6 subnet,
const ByteArray16 mask 
) const

Definition at line 340 of file IPAddressV6.cpp.

References folly::detail::Bytes::mask(), mask(), and toByteArray().

Referenced by inSubnet().

342  {
343  const auto mask = detail::Bytes::mask(toByteArray(), cidrMask);
344  const auto subMask = detail::Bytes::mask(subnet.toByteArray(), cidrMask);
345  return (mask == subMask);
346 }
ByteArray16 toByteArray() const
Definition: IPAddressV6.h:306
static std::array< uint8_t, N > mask(const std::array< uint8_t, N > &a, const std::array< uint8_t, N > &b)
IPAddressV6 mask(size_t numBits) const
bool folly::IPAddressV6::is6To4 ( ) const
inline

Definition at line 170 of file IPAddressV6.h.

References type().

Referenced by getIPv4For6To4(), and folly::toAppend().

170  {
171  return type() == IPAddressV6::Type::T6TO4;
172  }
Type type() const
bool folly::IPAddressV6::isIPv4Mapped ( ) const

Definition at line 273 of file IPAddressV6.cpp.

References bytes(), and i.

Referenced by createIPv4(), hash(), isLoopback(), isPrivate(), and isTeredo().

273  {
274  // v4 mapped addresses have their first 10 bytes set to 0, the next 2 bytes
275  // set to 255 (0xff);
276  const unsigned char* by = bytes();
277 
278  // check if first 10 bytes are 0
279  for (int i = 0; i < 10; i++) {
280  if (by[i] != 0x00) {
281  return false;
282  }
283  }
284  // check if bytes 11 and 12 are 255
285  if (by[10] == 0xff && by[11] == 0xff) {
286  return true;
287  }
288  return false;
289 }
const unsigned char * bytes() const
Definition: IPAddressV6.h:367
bool folly::IPAddressV6::isLinkLocal ( ) const

Return true if this is a link-local IPv6 address.

Note that this only returns true for addresses in the fe80::/10 range. It returns false for the loopback address (::1), even though this address is also effectively has link-local scope. It also returns false for link-scope and interface-scope multicast addresses.

Definition at line 382 of file IPAddressV6.cpp.

References inBinarySubnet().

Referenced by getMacAddressFromLinkLocal(), and isNonroutable().

382  {
383  return inBinarySubnet({{0xfe, 0x80}}, 10);
384 }
bool inBinarySubnet(const std::array< uint8_t, 2 > addr, size_t numBits) const
bool folly::IPAddressV6::isLinkLocalBroadcast ( ) const

Definition at line 367 of file IPAddressV6.cpp.

Referenced by isZero().

367  {
368  static const IPAddressV6 kLinkLocalBroadcast("ff02::1");
369  return *this == kLinkLocalBroadcast;
370 }
bool folly::IPAddressV6::isLoopback ( ) const

Definition at line 349 of file IPAddressV6.cpp.

References createIPv4(), isIPv4Mapped(), and toSockAddr().

Referenced by inSubnet(), and isPrivate().

349  {
350  // Check if v4 mapped is loopback
351  if (isIPv4Mapped() && createIPv4().isLoopback()) {
352  return true;
353  }
354  auto socka = toSockAddr();
355  return IN6_IS_ADDR_LOOPBACK(&socka.sin6_addr);
356 }
IPAddressV4 createIPv4() const
sockaddr_in6 toSockAddr() const
Definition: IPAddressV6.h:297
bool isLoopback() const
bool isIPv4Mapped() const
bool folly::IPAddressV6::isMulticast ( ) const

Return true if this is a multicast address.

Definition at line 386 of file IPAddressV6.cpp.

References addr_, and folly::IPAddressV6::AddressStorage::bytes_.

Referenced by folly::MacAddress::createMulticast(), getMulticastFlags(), getMulticastScope(), getSolicitedNodeAddress(), isNonroutable(), and isRoutable().

386  {
387  return addr_.bytes_[0] == 0xff;
388 }
union folly::IPAddressV6::AddressStorage addr_
bool folly::IPAddressV6::isNonroutable ( ) const
inline
bool folly::IPAddressV6::isPrivate ( ) const

Definition at line 373 of file IPAddressV6.cpp.

References createIPv4(), inBinarySubnet(), isIPv4Mapped(), and isLoopback().

Referenced by isNonroutable().

373  {
374  // Check if mapped is private
375  if (isIPv4Mapped() && createIPv4().isPrivate()) {
376  return true;
377  }
378  return isLoopback() || inBinarySubnet({{0xfc, 0x00}}, 7);
379 }
IPAddressV4 createIPv4() const
bool inBinarySubnet(const std::array< uint8_t, 2 > addr, size_t numBits) const
bool isLoopback() const
bool isPrivate() const
bool isIPv4Mapped() const
bool folly::IPAddressV6::isRoutable ( ) const

Return true if this address is routable.

Definition at line 358 of file IPAddressV6.cpp.

References getMulticastScope(), inBinarySubnet(), and isMulticast().

Referenced by isNonroutable().

358  {
359  return
360  // 2000::/3 is the only assigned global unicast block
361  inBinarySubnet({{0x20, 0x00}}, 3) ||
362  // ffxe::/16 are global scope multicast addresses,
363  // which are eligible to be routed over the internet
364  (isMulticast() && getMulticastScope() == 0xe);
365 }
bool inBinarySubnet(const std::array< uint8_t, 2 > addr, size_t numBits) const
bool isMulticast() const
uint8_t getMulticastScope() const
bool folly::IPAddressV6::isTeredo ( ) const
inline

Definition at line 175 of file IPAddressV6.h.

References isIPv4Mapped(), and type().

175  {
176  return type() == IPAddressV6::Type::TEREDO;
177  }
Type type() const
bool folly::IPAddressV6::isZero ( ) const
inline

Definition at line 275 of file IPAddressV6.h.

References bytes(), isLinkLocalBroadcast(), and mask().

275  {
276  constexpr auto zero = ByteArray16{{}};
277  return 0 == std::memcmp(bytes(), zero.data(), zero.size());
278  }
const unsigned char * bytes() const
Definition: IPAddressV6.h:367
std::array< uint8_t, 16 > ByteArray16
Definition: IPAddressV6.h:50
CIDRNetworkV6 folly::IPAddressV6::longestCommonPrefix ( const CIDRNetworkV6 one,
const CIDRNetworkV6 two 
)
static

Definition at line 521 of file IPAddressV6.cpp.

References IPAddressV6(), folly::detail::Bytes::longestCommonPrefix(), and prefix().

Referenced by folly::operator<(), TEST(), and version().

523  {
525  one.first.addr_.bytes_, one.second, two.first.addr_.bytes_, two.second);
526  return {IPAddressV6(prefix.first), prefix.second};
527 }
bool prefix(Cursor &c, uint32_t expected)
static std::pair< std::array< uint8_t, N >, uint8_t > longestCommonPrefix(const std::array< uint8_t, N > &one, uint8_t oneMask, const std::array< uint8_t, N > &two, uint8_t twoMask)
IPAddressV6 folly::IPAddressV6::mask ( size_t  numBits) const

Definition at line 427 of file IPAddressV6.cpp.

References addr_, bitCount(), folly::IPAddressV6::AddressStorage::bytes_, fetchMask(), IPAddressV6(), folly::detail::Bytes::mask(), and folly::sformat().

Referenced by inBinarySubnet(), inSubnet(), inSubnetWithMask(), and isZero().

427  {
428  static const auto bits = bitCount();
429  if (numBits > bits) {
430  throw IPAddressFormatException(
431  sformat("numBits({}) > bitCount({})", numBits, bits));
432  }
434  return IPAddressV6(ba);
435 }
std::string sformat(StringPiece fmt, Args &&...args)
Definition: Format.h:280
static constexpr size_t bitCount()
Definition: IPAddressV6.h:189
static std::array< uint8_t, N > mask(const std::array< uint8_t, N > &a, const std::array< uint8_t, N > &b)
static const ByteArray16 fetchMask(size_t numBits)
std::array< uint8_t, 16 > ByteArray16
Definition: IPAddressV6.h:50
union folly::IPAddressV6::AddressStorage addr_
void folly::IPAddressV6::setScopeId ( uint16_t  scope)
inline

Definition at line 293 of file IPAddressV6.h.

References scope_.

Referenced by TEST().

293  {
294  scope_ = scope;
295  }
string folly::IPAddressV6::str ( ) const

Definition at line 438 of file IPAddressV6.cpp.

References buffer(), bytes(), folly::errnoStr(), getScopeId(), folly::sformat(), string, toAddr(), and folly::detail::Bytes::toHex().

Referenced by getIPv4For6To4(), folly::operator<<(), TEST(), folly::toAppend(), toByteArray(), toJson(), and tryFromString().

438  {
439  char buffer[INET6_ADDRSTRLEN + IFNAMSIZ + 1];
440 
441  if (!inet_ntop(AF_INET6, toAddr().s6_addr, buffer, INET6_ADDRSTRLEN)) {
442  throw IPAddressFormatException(sformat(
443  "Invalid address with hex '{}' with error {}",
445  errnoStr(errno)));
446  }
447 
448  auto scopeId = getScopeId();
449  if (scopeId != 0) {
450  auto len = strlen(buffer);
451  buffer[len] = '%';
452 
453  auto errsv = errno;
454  if (!if_indextoname(scopeId, buffer + len + 1)) {
455  // if we can't map the if because eg. it no longer exists,
456  // append the if index instead
457  snprintf(buffer + len + 1, IFNAMSIZ, "%u", scopeId);
458  }
459  errno = errsv;
460  }
461 
462  return string(buffer);
463 }
std::vector< uint8_t > buffer(kBufferSize+16)
const unsigned char * bytes() const
Definition: IPAddressV6.h:367
std::string sformat(StringPiece fmt, Args &&...args)
Definition: Format.h:280
uint16_t getScopeId() const
Definition: IPAddressV6.h:290
fbstring errnoStr(int err)
Definition: String.cpp:463
const char * string
Definition: Conv.cpp:212
static std::string toHex(const uint8_t *src, std::size_t len)
in6_addr toAddr() const
Definition: IPAddressV6.h:286
auto folly::IPAddressV6::tie ( ) const
inlineprivate

Definition at line 379 of file IPAddressV6.h.

References addr_, folly::IPAddressV6::AddressStorage::bytes_, and scope_.

379  {
380  return std::tie(addr_.bytes_, scope_);
381  }
union folly::IPAddressV6::AddressStorage addr_
in6_addr folly::IPAddressV6::toAddr ( ) const
inline

Definition at line 286 of file IPAddressV6.h.

References addr_, and folly::IPAddressV6::AddressStorage::in6Addr_.

Referenced by BENCHMARK(), and str().

286  {
287  return addr_.in6Addr_;
288  }
union folly::IPAddressV6::AddressStorage addr_
ByteRange folly::IPAddressV6::toBinary ( ) const
inline

Returns the address as a Range.

Definition at line 129 of file IPAddressV6.h.

References addr_, createIPv4(), getIPv4For6To4(), folly::IPAddressV6::AddressStorage::in6Addr_, IPAddressV6(), and folly::pushmi::__adl::noexcept().

129  {
130  return ByteRange((const unsigned char*)&addr_.in6Addr_.s6_addr, 16);
131  }
Range< const unsigned char * > ByteRange
Definition: Range.h:1163
union folly::IPAddressV6::AddressStorage addr_
ByteArray16 folly::IPAddressV6::toByteArray ( ) const
inline

Definition at line 306 of file IPAddressV6.h.

References bytes(), str(), string, toFullyQualified(), toFullyQualifiedAppend(), and toInverseArpaName().

Referenced by inSubnetWithMask().

306  {
307  ByteArray16 ba{{0}};
308  std::memcpy(ba.data(), bytes(), 16);
309  return ba;
310  }
const unsigned char * bytes() const
Definition: IPAddressV6.h:367
std::array< uint8_t, 16 > ByteArray16
Definition: IPAddressV6.h:50
string folly::IPAddressV6::toFullyQualified ( ) const

Definition at line 466 of file IPAddressV6.cpp.

References addr_, folly::detail::fastIpv6ToString(), and folly::IPAddressV6::AddressStorage::in6Addr_.

Referenced by BENCHMARK(), BENCHMARK_RELATIVE(), and toByteArray().

466  {
468 }
std::string fastIpv6ToString(const in6_addr &in6Addr)
union folly::IPAddressV6::AddressStorage addr_
void folly::IPAddressV6::toFullyQualifiedAppend ( std::string out) const

Definition at line 471 of file IPAddressV6.cpp.

References addr_, folly::detail::fastIpv6AppendToString(), and folly::IPAddressV6::AddressStorage::in6Addr_.

Referenced by BENCHMARK_RELATIVE(), and toByteArray().

471  {
473 }
void fastIpv6AppendToString(const in6_addr &in6Addr, std::string &out)
union folly::IPAddressV6::AddressStorage addr_
string folly::IPAddressV6::toInverseArpaName ( ) const

Definition at line 476 of file IPAddressV6.cpp.

References a, bytes(), i, folly::join(), and folly::sformat().

Referenced by toByteArray().

476  {
477  constexpr folly::StringPiece lut = "0123456789abcdef";
478  std::array<char, 32> a;
479  int j = 0;
480  for (int i = 15; i >= 0; i--) {
481  a[j] = (lut[bytes()[i] & 0xf]);
482  a[j + 1] = (lut[bytes()[i] >> 4]);
483  j += 2;
484  }
485  return sformat("{}.ip6.arpa", join(".", a));
486 }
const unsigned char * bytes() const
Definition: IPAddressV6.h:367
std::string sformat(StringPiece fmt, Args &&...args)
Definition: Format.h:280
char a
void join(const Delim &delimiter, Iterator begin, Iterator end, String &output)
Definition: String-inl.h:498
string folly::IPAddressV6::toJson ( ) const
See also
IPAddress::toJson

Definition at line 309 of file IPAddressV6.cpp.

References hash(), folly::sformat(), and str().

Referenced by bitCount().

309  {
310  return sformat("{{family:'AF_INET6', addr:'{}', hash:{}}}", str(), hash());
311 }
std::string sformat(StringPiece fmt, Args &&...args)
Definition: Format.h:280
std::string str() const
size_t hash() const
sockaddr_in6 folly::IPAddressV6::toSockAddr ( ) const
inline

Definition at line 297 of file IPAddressV6.h.

References addr, addr_, folly::IPAddressV6::AddressStorage::in6Addr_, and scope_.

Referenced by isLoopback(), and TEST().

297  {
298  sockaddr_in6 addr;
299  memset(&addr, 0, sizeof(sockaddr_in6));
300  addr.sin6_family = AF_INET6;
301  addr.sin6_scope_id = scope_;
302  memcpy(&addr.sin6_addr, &addr_.in6Addr_, sizeof(in6_addr));
303  return addr;
304  }
ThreadPoolListHook * addr
union folly::IPAddressV6::AddressStorage addr_
Expected< IPAddressV6, IPAddressFormatError > folly::IPAddressV6::tryFromBinary ( ByteRange  bytes)
staticnoexcept

Non-throwing version of fromBinary(). On failure returns IPAddressFormatError.

Definition at line 178 of file IPAddressV6.cpp.

References addr, bytes(), folly::makeUnexpected(), folly::gen::move, and trySetFromBinary().

Referenced by fromBinary(), TEST(), TEST_P(), and folly::toAppend().

179  {
181  auto setResult = addr.trySetFromBinary(bytes);
182  if (setResult.hasError()) {
183  return makeUnexpected(std::move(setResult.error()));
184  }
185  return addr;
186 }
const unsigned char * bytes() const
Definition: IPAddressV6.h:367
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
constexpr Unexpected< typename std::decay< Error >::type > makeUnexpected(Error &&)
Definition: Expected.h:785
ThreadPoolListHook * addr
Expected< IPAddressV6, IPAddressFormatError > folly::IPAddressV6::tryFromString ( StringPiece  str)
staticnoexcept

Tries to create a new IPAddressV6 instance from provided string and returns it on success. Returns IPAddressFormatError on failure.

Definition at line 82 of file IPAddressV6.cpp.

References folly::INVALID_IP, IPAddressV6(), folly::makeUnexpected(), SCOPE_EXIT, and str().

Referenced by BENCHMARK(), BENCHMARK_RELATIVE(), IPAddressV6(), TEST_P(), and folly::toAppend().

83  {
84  auto ip = str.str();
85 
86  // Allow addresses surrounded in brackets
87  if (ip.size() < 2) {
89  }
90  if (ip.front() == '[' && ip.back() == ']') {
91  ip = ip.substr(1, ip.size() - 2);
92  }
93 
94  struct addrinfo* result;
95  struct addrinfo hints;
96  memset(&hints, 0, sizeof(hints));
97  hints.ai_family = AF_INET6;
98  hints.ai_socktype = SOCK_STREAM;
99  hints.ai_flags = AI_NUMERICHOST;
100  if (::getaddrinfo(ip.c_str(), nullptr, &hints, &result) == 0) {
101  SCOPE_EXIT {
102  ::freeaddrinfo(result);
103  };
104  const struct sockaddr_in6* sa =
105  reinterpret_cast<struct sockaddr_in6*>(result->ai_addr);
106  return IPAddressV6(*sa);
107  }
109 }
#define SCOPE_EXIT
Definition: ScopeGuard.h:274
constexpr Unexpected< typename std::decay< Error >::type > makeUnexpected(Error &&)
Definition: Expected.h:785
std::string str() const
Expected< Unit, IPAddressFormatError > folly::IPAddressV6::trySetFromBinary ( ByteRange  bytes)
privatenoexcept

Set the current IPAddressV6 object to have the address specified by bytes. Returns IPAddressFormatError if bytes.size() is not 16.

Definition at line 188 of file IPAddressV6.cpp.

References addr_, bytes(), folly::IPAddressV6::AddressStorage::in6Addr_, folly::INVALID_IP, folly::makeUnexpected(), scope_, and folly::unit.

Referenced by tryFromBinary().

189  {
190  if (bytes.size() != 16) {
192  }
193  memcpy(&addr_.in6Addr_.s6_addr, bytes.data(), sizeof(in6_addr));
194  scope_ = 0;
195  return unit;
196 }
const unsigned char * bytes() const
Definition: IPAddressV6.h:367
constexpr Unexpected< typename std::decay< Error >::type > makeUnexpected(Error &&)
Definition: Expected.h:785
constexpr Unit unit
Definition: Unit.h:45
union folly::IPAddressV6::AddressStorage addr_
IPAddressV6::Type folly::IPAddressV6::type ( ) const

Definition at line 292 of file IPAddressV6.cpp.

References bytes(), folly::NORMAL, uint16_t, uint32_t, and folly::unpackInto().

Referenced by is6To4(), and isTeredo().

292  {
293  // convert 16x8 bytes into first 2x16 bytes
294  uint16_t ints[2] = {0, 0};
295  unpackInto(bytes(), ints, 2);
296 
297  if ((((uint32_t)ints[0] << 16) | ints[1]) == IPAddressV6::PREFIX_TEREDO) {
298  return Type::TEREDO;
299  }
300 
301  if ((uint32_t)ints[0] == IPAddressV6::PREFIX_6TO4) {
302  return Type::T6TO4;
303  }
304 
305  return Type::NORMAL;
306 }
static const uint32_t PREFIX_6TO4
Definition: IPAddressV6.h:90
const unsigned char * bytes() const
Definition: IPAddressV6.h:367
static void unpackInto(const unsigned char *src, uint16_t *dest, size_t count)
static const uint32_t PREFIX_TEREDO
Definition: IPAddressV6.h:88
bool folly::IPAddressV6::validate ( StringPiece  ip)
staticnoexcept

Definition at line 65 of file IPAddressV6.cpp.

Referenced by TEST(), and folly::toAppend().

65  {
66  return tryFromString(ip).hasValue();
67 }
static Expected< IPAddressV6, IPAddressFormatError > tryFromString(StringPiece str) noexcept
Definition: IPAddressV6.cpp:82
uint8_t folly::IPAddressV6::version ( ) const
inline

Definition at line 324 of file IPAddressV6.h.

References fetchMask(), getSolicitedNodeAddress(), and longestCommonPrefix().

324  {
325  return 6;
326  }

Friends And Related Function Documentation

bool operator!= ( const IPAddressV6 a,
const IPAddressV6 b 
)
friend

Definition at line 387 of file IPAddressV6.h.

387  {
388  return a.tie() != b.tie();
389  }
char b
char a
bool operator< ( const IPAddressV6 a,
const IPAddressV6 b 
)
friend

Definition at line 390 of file IPAddressV6.h.

390  {
391  return a.tie() < b.tie();
392  }
char b
char a
bool operator<= ( const IPAddressV6 a,
const IPAddressV6 b 
)
friend

Definition at line 396 of file IPAddressV6.h.

396  {
397  return a.tie() <= b.tie();
398  }
char b
char a
bool operator== ( const IPAddressV6 a,
const IPAddressV6 b 
)
friend

Definition at line 384 of file IPAddressV6.h.

384  {
385  return a.tie() == b.tie();
386  }
char b
char a
bool operator> ( const IPAddressV6 a,
const IPAddressV6 b 
)
friend

Definition at line 393 of file IPAddressV6.h.

393  {
394  return a.tie() > b.tie();
395  }
char b
char a
bool operator>= ( const IPAddressV6 a,
const IPAddressV6 b 
)
friend

Definition at line 399 of file IPAddressV6.h.

399  {
400  return a.tie() >= b.tie();
401  }
char b
char a

Member Data Documentation

constexpr size_t folly::IPAddressV6::kToFullyQualifiedSize
static
Initial value:
=
8 * 4 + 7

Definition at line 93 of file IPAddressV6.h.

Referenced by BENCHMARK_RELATIVE(), and TEST().

const uint32_t folly::IPAddressV6::PREFIX_6TO4 = 0x2002
static

Definition at line 90 of file IPAddressV6.h.

Referenced by folly::IPAddressV4::getIPv6For6To4().

const uint32_t folly::IPAddressV6::PREFIX_TEREDO = 0x20010000
static

Definition at line 88 of file IPAddressV6.h.

uint16_t folly::IPAddressV6::scope_ {0}
private

Definition at line 417 of file IPAddressV6.h.

Referenced by getScopeId(), setScopeId(), tie(), toSockAddr(), and trySetFromBinary().


The documentation for this class was generated from the following files: