proxygen
folly::SocketAddress Class Reference

#include <SocketAddress.h>

Classes

union  AddrStorage
 
struct  ExternalUnixAddr
 

Public Member Functions

 SocketAddress ()=default
 
 SocketAddress (const char *host, uint16_t port, bool allowNameLookup=false)
 
 SocketAddress (const std::string &host, uint16_t port, bool allowNameLookup=false)
 
 SocketAddress (const IPAddress &ipAddr, uint16_t port)
 
 SocketAddress (const SocketAddress &addr)
 
SocketAddressoperator= (const SocketAddress &addr)
 
 SocketAddress (SocketAddress &&addr) noexcept
 
SocketAddressoperator= (SocketAddress &&addr)
 
 ~SocketAddress ()
 
bool isInitialized () const
 
bool isPrivateAddress () const
 
bool isLoopbackAddress () const
 
void reset ()
 
void setFromHostPort (const char *host, uint16_t port)
 
void setFromHostPort (const std::string &host, uint16_t port)
 
void setFromIpPort (const char *ip, uint16_t port)
 
void setFromIpPort (const std::string &ip, uint16_t port)
 
void setFromIpAddrPort (const IPAddress &ip, uint16_t port)
 
void setFromLocalPort (uint16_t port)
 
void setFromLocalPort (const char *port)
 
void setFromLocalPort (const std::string &port)
 
void setFromLocalIpPort (const char *addressAndPort)
 
void setFromLocalIpPort (const std::string &addressAndPort)
 
void setFromIpPort (const char *addressAndPort)
 
void setFromIpPort (const std::string &addressAndPort)
 
void setFromHostPort (const char *hostAndPort)
 
void setFromHostPort (const std::string &hostAndPort)
 
void setFromPath (StringPiece path)
 
void setFromPath (const char *path, size_t length)
 
void setFromPeerAddress (int socket)
 
void setFromPeerAddress (NetworkSocket socket)
 
void setFromLocalAddress (int socket)
 
void setFromLocalAddress (NetworkSocket socket)
 
void setFromSockaddr (const struct sockaddr *address)
 
void setFromSockaddr (const struct sockaddr *address, socklen_t addrlen)
 
void setFromSockaddr (const struct sockaddr_in *address)
 
void setFromSockaddr (const struct sockaddr_in6 *address)
 
void setFromSockaddr (const struct sockaddr_un *address, socklen_t addrlen)
 
socklen_t getAddress (sockaddr_storage *addr) const
 
const folly::IPAddress & getIPAddress () const
 
socklen_t getActualSize () const
 
sa_family_t getFamily () const
 
bool empty () const
 
std::string getAddressStr () const
 
void getAddressStr (char *buf, size_t buflen) const
 
bool isFamilyInet () const
 
std::string getFullyQualified () const
 
uint16_t getPort () const
 
void setPort (uint16_t port)
 
bool isIPv4Mapped () const
 
void convertToIPv4 ()
 
bool tryConvertToIPv4 ()
 
bool mapToIPv6 ()
 
std::string getHostStr () const
 
std::string getPath () const
 
std::string describe () const
 
bool operator== (const SocketAddress &other) const
 
bool operator!= (const SocketAddress &other) const
 
bool prefixMatch (const SocketAddress &other, unsigned prefixLength) const
 
bool operator< (const SocketAddress &other) const
 
size_t hash () const
 

Static Public Member Functions

static int getPortFrom (const struct sockaddr *address)
 
static const char * getFamilyNameFrom (const struct sockaddr *address, const char *defaultResult=nullptr)
 
static SocketAddress makeFromPath (StringPiece path)
 

Private Member Functions

struct addrinfo * getAddrInfo (const char *host, uint16_t port, int flags)
 
struct addrinfo * getAddrInfo (const char *host, const char *port, int flags)
 
void setFromAddrInfo (const struct addrinfo *results)
 
void setFromLocalAddr (const struct addrinfo *results)
 
void setFromSocket (NetworkSocket socket, int(*fn)(NetworkSocket, struct sockaddr *, socklen_t *))
 
std::string getIpString (int flags) const
 
void getIpString (char *buf, size_t buflen, int flags) const
 
void updateUnixAddressLength (socklen_t addrlen)
 

Private Attributes

union folly::SocketAddress::AddrStorage storage_
 
uint16_t port_
 
bool external_ {false}
 

Detailed Description

Definition at line 32 of file SocketAddress.h.

Constructor & Destructor Documentation

folly::SocketAddress::SocketAddress ( )
default
folly::SocketAddress::SocketAddress ( const char *  host,
uint16_t  port,
bool  allowNameLookup = false 
)
inline

Construct a SocketAddress from a hostname and port.

Note: If the host parameter is not a numeric IP address, hostname resolution will be performed, which can be quite slow.

Raises std::system_error on error.

Parameters
hostThe IP address (or hostname, if allowNameLookup is true)
portThe port (in host byte order) allowNameLookup If true, attempt to perform hostname lookup if the hostname does not appear to be a numeric IP address. This is potentially a very slow operation, so is disabled by default.

Definition at line 51 of file SocketAddress.h.

References setFromHostPort(), and setFromIpPort().

51  {
52  // Initialize the address family first,
53  // since setFromHostPort() and setFromIpPort() will check it.
54 
55  if (allowNameLookup) {
56  setFromHostPort(host, port);
57  } else {
58  setFromIpPort(host, port);
59  }
60  }
void setFromHostPort(const char *host, uint16_t port)
void setFromIpPort(const char *ip, uint16_t port)
folly::SocketAddress::SocketAddress ( const std::string host,
uint16_t  port,
bool  allowNameLookup = false 
)
inline

Definition at line 62 of file SocketAddress.h.

References setFromHostPort(), and setFromIpPort().

65  {
66  // Initialize the address family first,
67  // since setFromHostPort() and setFromIpPort() will check it.
68 
69  if (allowNameLookup) {
70  setFromHostPort(host.c_str(), port);
71  } else {
72  setFromIpPort(host.c_str(), port);
73  }
74  }
void setFromHostPort(const char *host, uint16_t port)
void setFromIpPort(const char *ip, uint16_t port)
folly::SocketAddress::SocketAddress ( const IPAddress &  ipAddr,
uint16_t  port 
)
inline

Definition at line 76 of file SocketAddress.h.

References setFromIpAddrPort().

76  {
77  setFromIpAddrPort(ipAddr, port);
78  }
void setFromIpAddrPort(const IPAddress &ip, uint16_t port)
folly::SocketAddress::SocketAddress ( const SocketAddress addr)
inline

Definition at line 80 of file SocketAddress.h.

References external_, getFamily(), folly::SocketAddress::ExternalUnixAddr::init(), port_, storage_, and folly::SocketAddress::AddrStorage::un.

80  {
81  port_ = addr.port_;
82  if (addr.getFamily() == AF_UNIX) {
83  storage_.un.init(addr.storage_.un);
84  } else {
85  storage_ = addr.storage_;
86  }
87  external_ = addr.external_;
88  }
union folly::SocketAddress::AddrStorage storage_
ThreadPoolListHook * addr
folly::SocketAddress::SocketAddress ( SocketAddress &&  addr)
inlinenoexcept

Definition at line 111 of file SocketAddress.h.

References addr, external_, port_, and storage_.

111  {
112  storage_ = addr.storage_;
113  port_ = addr.port_;
114  external_ = addr.external_;
115  addr.external_ = false;
116  }
union folly::SocketAddress::AddrStorage storage_
ThreadPoolListHook * addr
folly::SocketAddress::~SocketAddress ( )
inline

Definition at line 125 of file SocketAddress.h.

References external_, folly::SocketAddress::ExternalUnixAddr::free(), storage_, and folly::SocketAddress::AddrStorage::un.

125  {
126  if (external_) {
127  storage_.un.free();
128  }
129  }
union folly::SocketAddress::AddrStorage storage_

Member Function Documentation

void folly::SocketAddress::convertToIPv4 ( )

Convert an IPv4-mapped IPv6 address to an IPv4 address.

Raises std::invalid_argument if this is not an IPv4-mapped IPv6 address.

Definition at line 430 of file SocketAddress.cpp.

Referenced by isIPv4Mapped(), and TEST().

430  {
431  if (!tryConvertToIPv4()) {
432  throw std::invalid_argument(
433  "convertToIPv4() called on an addresse that is "
434  "not an IPv4-mapped address");
435  }
436 }
std::string folly::SocketAddress::describe ( ) const

Get human-readable string representation of the address.

This prints a string representation of the address, for human consumption. For IP addresses, the string is of the form "<IP>:<port>".

Definition at line 482 of file SocketAddress.cpp.

References string.

Referenced by wangle::SSLContextManager::addSSLContextConfig(), folly::AsyncUDPSocket::bind(), folly::AsyncServerSocket::bindSocket(), wangle::Acceptor::canAccept(), folly::AsyncSocket::fail(), folly::AsyncSocket::failConnect(), folly::AsyncSocket::failErrMessageRead(), folly::AsyncSocket::failRead(), folly::AsyncSocket::failWrite(), folly::AsyncSocket::handleConnect(), isIPv4Mapped(), proxygen::HTTPSessionAcceptor::onNewConnection(), folly::operator<<(), folly::AsyncServerSocket::setupSocket(), proxygen::HTTPSession::shutdownTransport(), TEST(), TelnetHandler::transportActive(), FileServerHandler::transportActive(), and folly::AsyncSocket::withAddr().

482  {
483  if (external_) {
484  if (storage_.un.pathLength() == 0) {
485  return "<anonymous unix address>";
486  }
487 
488  if (storage_.un.addr->sun_path[0] == '\0') {
489  // Linux supports an abstract namespace for unix socket addresses
490  return "<abstract unix address>";
491  }
492 
493  return std::string(
494  storage_.un.addr->sun_path,
495  strnlen(storage_.un.addr->sun_path, size_t(storage_.un.pathLength())));
496  }
497  switch (getFamily()) {
498  case AF_UNSPEC:
499  return "<uninitialized address>";
500  case AF_INET: {
501  char buf[NI_MAXHOST + 16];
502  getAddressStr(buf, sizeof(buf));
503  size_t iplen = strlen(buf);
504  snprintf(buf + iplen, sizeof(buf) - iplen, ":%" PRIu16, getPort());
505  return buf;
506  }
507  case AF_INET6: {
508  char buf[NI_MAXHOST + 18];
509  buf[0] = '[';
510  getAddressStr(buf + 1, sizeof(buf) - 1);
511  size_t iplen = strlen(buf);
512  snprintf(buf + iplen, sizeof(buf) - iplen, "]:%" PRIu16, getPort());
513  return buf;
514  }
515  default: {
516  char buf[64];
517  snprintf(buf, sizeof(buf), "<unknown address family %d>", getFamily());
518  return buf;
519  }
520  }
521 }
uint16_t getPort() const
sa_family_t getFamily() const
union folly::SocketAddress::AddrStorage storage_
const char * string
Definition: Conv.cpp:212
std::string getAddressStr() const
bool folly::SocketAddress::empty ( ) const
inline

Definition at line 412 of file SocketAddress.h.

References getAddressStr(), getFamily(), getFullyQualified(), getPort(), isFamilyInet(), setPort(), string, and uint16_t.

Referenced by TEST().

412  {
413  return getFamily() == AF_UNSPEC;
414  }
sa_family_t getFamily() const
socklen_t folly::SocketAddress::getActualSize ( ) const

Definition at line 362 of file SocketAddress.cpp.

Referenced by folly::AsyncUDPSocket::bind(), folly::AsyncServerSocket::bindSocket(), folly::AsyncUDPSocket::connect(), folly::AsyncSocket::connect(), getAddress(), testSetFromSocket(), and folly::AsyncUDPSocket::writev().

362  {
363  if (external_) {
364  return storage_.un.len;
365  }
366  switch (getFamily()) {
367  case AF_UNSPEC:
368  case AF_INET:
369  return sizeof(struct sockaddr_in);
370  case AF_INET6:
371  return sizeof(struct sockaddr_in6);
372  default:
373  throw std::invalid_argument(
374  "SocketAddress::getActualSize() called "
375  "with unrecognized address family");
376  }
377 }
sa_family_t getFamily() const
union folly::SocketAddress::AddrStorage storage_
socklen_t folly::SocketAddress::getAddress ( sockaddr_storage *  addr) const
inline

Fill in a given sockaddr_storage with the ip or unix address.

Returns the actual size of the storage used.

Definition at line 393 of file SocketAddress.h.

References folly::SocketAddress::ExternalUnixAddr::addr, folly::SocketAddress::AddrStorage::addr, external_, getActualSize(), getIPAddress(), folly::SocketAddress::ExternalUnixAddr::len, port_, storage_, and folly::SocketAddress::AddrStorage::un.

Referenced by folly::AsyncUDPSocket::bind(), folly::AsyncServerSocket::bindSocket(), folly::AsyncUDPSocket::connect(), folly::AsyncSocket::sendSocketMessage(), folly::TEST(), TEST(), testSetFromSocket(), and folly::AsyncUDPSocket::writev().

393  {
394  if (!external_) {
395  return storage_.addr.toSockaddrStorage(addr, htons(port_));
396  } else {
397  memcpy(addr, storage_.un.addr, sizeof(*storage_.un.addr));
398  return storage_.un.len;
399  }
400  }
union folly::SocketAddress::AddrStorage storage_
ThreadPoolListHook * addr
std::string folly::SocketAddress::getAddressStr ( ) const

Get a string representation of the IPv4 or IPv6 address.

Raises std::invalid_argument if an error occurs (for example, if the address is not an IPv4 or IPv6 address).

Definition at line 386 of file SocketAddress.cpp.

Referenced by empty(), main(), proxygen::HTTPMessage::setClientAddress(), proxygen::HTTPMessage::setDstAddress(), and TEST().

386  {
387  if (!isFamilyInet()) {
388  throw std::invalid_argument("Can't get address str for non ip address");
389  }
390  return storage_.addr.str();
391 }
bool isFamilyInet() const
union folly::SocketAddress::AddrStorage storage_
void folly::SocketAddress::getAddressStr ( char *  buf,
size_t  buflen 
) const

Get a string representation of the IPv4 or IPv6 address.

Raises std::invalid_argument if an error occurs (for example, if the address is not an IPv4 or IPv6 address).

Definition at line 398 of file SocketAddress.cpp.

References min.

398  {
399  auto ret = getAddressStr();
400  size_t len = std::min(buflen - 1, ret.size());
401  memcpy(buf, ret.data(), len);
402  buf[len] = '\0';
403 }
LogLevel min
Definition: LogLevel.cpp:30
std::string getAddressStr() const
struct addrinfo * folly::SocketAddress::getAddrInfo ( const char *  host,
uint16_t  port,
int  flags 
)
private

Definition at line 609 of file SocketAddress.cpp.

Referenced by folly::SocketAddress::ExternalUnixAddr::free().

609  {
610  // getaddrinfo() requires the port number as a string
611  char portString[sizeof("65535")];
612  snprintf(portString, sizeof(portString), "%" PRIu16, port);
613 
614  return getAddrInfo(host, portString, flags);
615 }
flags
Definition: http_parser.h:127
struct addrinfo * getAddrInfo(const char *host, uint16_t port, int flags)
struct addrinfo * folly::SocketAddress::getAddrInfo ( const char *  host,
const char *  port,
int  flags 
)
private

Definition at line 618 of file SocketAddress.cpp.

References folly::pushmi::operators::error(), and folly::sformat().

618  {
619  struct addrinfo hints;
620  memset(&hints, 0, sizeof(hints));
621  hints.ai_family = AF_UNSPEC;
622  hints.ai_socktype = SOCK_STREAM;
623  hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV | flags;
624 
625  struct addrinfo* results;
626  int error = getaddrinfo(host, port, &hints, &results);
627  if (error != 0) {
628  auto os = folly::sformat(
629  "Failed to resolve address for '{}': {} (error={})",
630  host,
631  gai_strerror(error),
632  error);
633  throw std::system_error(error, std::generic_category(), os);
634  }
635 
636  return results;
637 }
flags
Definition: http_parser.h:127
std::string sformat(StringPiece fmt, Args &&...args)
Definition: Format.h:280
requires And< SemiMovable< VN >... > &&SemiMovable< E > auto error(E e)
Definition: error.h:48
const char * folly::SocketAddress::getFamilyNameFrom ( const struct sockaddr *  address,
const char *  defaultResult = nullptr 
)
static

Returns the family name from the given socketaddr structure (e.g.: AF_INET6 for IPv6).

Returns defaultResult for unsupported socket families.

Definition at line 199 of file SocketAddress.cpp.

References GETFAMILYNAMEFROM_IMPL.

Referenced by folly::AsyncServerSocket::bind(), and setFromHostPort().

201  {
202 #define GETFAMILYNAMEFROM_IMPL(Family) \
203  case Family: \
204  return #Family
205 
206  switch (address->sa_family) {
207  GETFAMILYNAMEFROM_IMPL(AF_INET);
208  GETFAMILYNAMEFROM_IMPL(AF_INET6);
209  GETFAMILYNAMEFROM_IMPL(AF_UNIX);
210  GETFAMILYNAMEFROM_IMPL(AF_UNSPEC);
211 
212  default:
213  return defaultResult;
214  }
215 
216 #undef GETFAMILYNAMEFROM_IMPL
217 }
#define GETFAMILYNAMEFROM_IMPL(Family)
std::string folly::SocketAddress::getFullyQualified ( ) const

For v4 & v6 addresses, return the fully qualified address string

Definition at line 379 of file SocketAddress.cpp.

Referenced by empty().

379  {
380  if (!isFamilyInet()) {
381  throw std::invalid_argument("Can't get address str for non ip address");
382  }
383  return storage_.addr.toFullyQualified();
384 }
bool isFamilyInet() const
union folly::SocketAddress::AddrStorage storage_
std::string folly::SocketAddress::getHostStr ( ) const

Get string representation of the host name (or IP address if the host name cannot be resolved).

Warning: Using this method is strongly discouraged. It performs a DNS lookup, which may block for many seconds.

Raises std::invalid_argument if an error occurs.

Definition at line 456 of file SocketAddress.cpp.

Referenced by isIPv4Mapped().

456  {
457  return getIpString(0);
458 }
std::string getIpString(int flags) const
const folly::IPAddress & folly::SocketAddress::getIPAddress ( ) const

Definition at line 354 of file SocketAddress.cpp.

Referenced by getAddress(), wangle::LoadShedConfiguration::AddressOnlyCompare::operator()(), and TEST().

354  {
355  auto family = getFamily();
356  if (family != AF_INET && family != AF_INET6) {
357  throw InvalidAddressFamilyException(family);
358  }
359  return storage_.addr;
360 }
sa_family_t getFamily() const
union folly::SocketAddress::AddrStorage storage_
std::string folly::SocketAddress::getIpString ( int  flags) const
private

Definition at line 670 of file SocketAddress.cpp.

References string.

Referenced by folly::SocketAddress::ExternalUnixAddr::free().

670  {
671  char addrString[NI_MAXHOST];
672  getIpString(addrString, sizeof(addrString), flags);
673  return std::string(addrString);
674 }
flags
Definition: http_parser.h:127
std::string getIpString(int flags) const
const char * string
Definition: Conv.cpp:212
void folly::SocketAddress::getIpString ( char *  buf,
size_t  buflen,
int  flags 
) const
private

Definition at line 676 of file SocketAddress.cpp.

References folly::sformat().

676  {
677  auto family = getFamily();
678  if (family != AF_INET && family != AF_INET6) {
679  throw std::invalid_argument(
680  "SocketAddress: attempting to get IP address "
681  "for a non-IP address");
682  }
683 
684  sockaddr_storage tmp_sock;
685  storage_.addr.toSockaddrStorage(&tmp_sock, port_);
686  int rc = getnameinfo(
687  (sockaddr*)&tmp_sock,
688  sizeof(sockaddr_storage),
689  buf,
690  buflen,
691  nullptr,
692  0,
693  flags);
694  if (rc != 0) {
695  auto os = sformat(
696  "getnameinfo() failed in getIpString() error = {}", gai_strerror(rc));
697  throw std::system_error(rc, std::generic_category(), os);
698  }
699 }
flags
Definition: http_parser.h:127
std::string sformat(StringPiece fmt, Args &&...args)
Definition: Format.h:280
sa_family_t getFamily() const
union folly::SocketAddress::AddrStorage storage_
std::string folly::SocketAddress::getPath ( ) const

Get the path name for a Unix domain socket.

Returns a std::string containing the path. For anonymous sockets, an empty string is returned.

For addresses in the abstract namespace (Linux-specific), a std::string containing binary data is returned. In this case the first character will always be a NUL character.

Raises std::invalid_argument if called on a non-Unix domain socket.

Definition at line 460 of file SocketAddress.cpp.

References string.

Referenced by isIPv4Mapped(), and TEST().

460  {
461  if (!external_) {
462  throw std::invalid_argument(
463  "SocketAddress: attempting to get path "
464  "for a non-Unix address");
465  }
466 
467  if (storage_.un.pathLength() == 0) {
468  // anonymous address
469  return std::string();
470  }
471  if (storage_.un.addr->sun_path[0] == '\0') {
472  // abstract namespace
473  return std::string(
474  storage_.un.addr->sun_path, size_t(storage_.un.pathLength()));
475  }
476 
477  return std::string(
478  storage_.un.addr->sun_path,
479  strnlen(storage_.un.addr->sun_path, size_t(storage_.un.pathLength())));
480 }
union folly::SocketAddress::AddrStorage storage_
const char * string
Definition: Conv.cpp:212
uint16_t folly::SocketAddress::getPort ( ) const

Get the IPv4 or IPv6 port for this address.

Raises std::invalid_argument if this is not an IPv4 or IPv6 address.

Returns
Returns the port, in host byte order.

Definition at line 405 of file SocketAddress.cpp.

Referenced by folly::AsyncUDPSocket::bind(), folly::AsyncServerSocket::bind(), empty(), proxygen::HTTPMessage::setClientAddress(), proxygen::HTTPMessage::setDstAddress(), folly::TEST(), and TEST().

405  {
406  switch (getFamily()) {
407  case AF_INET:
408  case AF_INET6:
409  return port_;
410  default:
411  throw std::invalid_argument(
412  "SocketAddress::getPort() called on non-IP "
413  "address");
414  }
415 }
sa_family_t getFamily() const
int folly::SocketAddress::getPortFrom ( const struct sockaddr *  address)
static

Returns the port number from the given socketaddr structure.

Currently only IPv4 and IPv6 are supported.

Returns -1 for unsupported socket families.

Definition at line 186 of file SocketAddress.cpp.

Referenced by folly::AsyncServerSocket::bind(), and setFromHostPort().

186  {
187  switch (address->sa_family) {
188  case AF_INET:
189  return ntohs(((sockaddr_in*)address)->sin_port);
190 
191  case AF_INET6:
192  return ntohs(((sockaddr_in6*)address)->sin6_port);
193 
194  default:
195  return -1;
196  }
197 }
size_t folly::SocketAddress::hash ( ) const

Compuate a hash of a SocketAddress.

Definition at line 575 of file SocketAddress.cpp.

References folly::hash::hash_combine(), seed, folly::hash::twang_mix64(), and uint64_t.

Referenced by folly::hash_value(), operator!=(), std::hash< folly::SocketAddress >::operator()(), and TEST().

575  {
577 
578  if (external_) {
579  enum { kUnixPathMax = sizeof(storage_.un.addr->sun_path) };
580  const char* path = storage_.un.addr->sun_path;
581  auto pathLength = storage_.un.pathLength();
582  // TODO: this probably could be made more efficient
583  for (off_t n = 0; n < pathLength; ++n) {
585  }
586  }
587 
588  switch (getFamily()) {
589  case AF_INET:
590  case AF_INET6: {
591  boost::hash_combine(seed, port_);
592  boost::hash_combine(seed, storage_.addr.hash());
593  break;
594  }
595  case AF_UNIX:
596  DCHECK(external_);
597  break;
598  case AF_UNSPEC:
599  default:
600  throw std::invalid_argument(
601  "SocketAddress: unsupported address family "
602  "for hashing");
603  }
604 
605  return seed;
606 }
static const int seed
sa_family_t getFamily() const
size_t hash_combine(const T &t, const Ts &...ts) noexcept(noexcept(hash_combine_generic(StdHasher{}, t, ts...)))
Definition: Hash.h:669
union folly::SocketAddress::AddrStorage storage_
uint64_t twang_mix64(uint64_t key) noexcept
Definition: Hash.h:49
bool folly::SocketAddress::isFamilyInet ( ) const

Return true if it is a valid IPv4 or IPv6 address.

Definition at line 393 of file SocketAddress.cpp.

Referenced by empty(), proxygen::HTTPSessionAcceptor::onNewConnection(), and TEST().

393  {
394  auto family = getFamily();
395  return family == AF_INET || family == AF_INET6;
396 }
sa_family_t getFamily() const
bool folly::SocketAddress::isInitialized ( ) const
inline

Definition at line 131 of file SocketAddress.h.

References getFamily(), isLoopbackAddress(), and isPrivateAddress().

Referenced by folly::AsyncSocket::cacheLocalAddress(), folly::AsyncSocket::cachePeerAddress(), and TEST().

131  {
132  return (getFamily() != AF_UNSPEC);
133  }
sa_family_t getFamily() const
bool folly::SocketAddress::isIPv4Mapped ( ) const
inline

Return true if this is an IPv4-mapped IPv6 address.

Definition at line 461 of file SocketAddress.h.

References folly::SocketAddress::AddrStorage::addr, convertToIPv4(), describe(), getFamily(), getHostStr(), getPath(), mapToIPv6(), operator==(), storage_, string, and tryConvertToIPv4().

Referenced by TEST().

461  {
462  return (getFamily() == AF_INET6 && storage_.addr.isIPv4Mapped());
463  }
sa_family_t getFamily() const
union folly::SocketAddress::AddrStorage storage_
bool folly::SocketAddress::isLoopbackAddress ( ) const

Return whether this address is a loopback address.

Definition at line 127 of file SocketAddress.cpp.

Referenced by isInitialized(), and TEST().

127  {
128  auto family = getFamily();
129  if (family == AF_INET || family == AF_INET6) {
130  return storage_.addr.isLoopback();
131  } else if (external_) {
132  // Return true for UNIX addresses, since they are always local to a host.
133  return true;
134  }
135  return false;
136 }
sa_family_t getFamily() const
union folly::SocketAddress::AddrStorage storage_
bool folly::SocketAddress::isPrivateAddress ( ) const

Return whether this address is within private network.

According to RFC1918, the 10/8 prefix, 172.16/12 prefix, and 192.168/16 prefix are reserved for private networks. fc00::/7 is the IPv6 version, defined in RFC4139. IPv6 link-local addresses (fe80::/10) are also considered private addresses.

The loopback addresses 127/8 and ::1 are also regarded as private networks for the purpose of this function.

Returns true if this is a private network address, and false otherwise.

Definition at line 113 of file SocketAddress.cpp.

Referenced by proxygen::HTTPSessionAcceptor::getErrorPage(), isInitialized(), and TEST().

113  {
114  auto family = getFamily();
115  if (family == AF_INET || family == AF_INET6) {
116  return storage_.addr.isPrivate() ||
117  (storage_.addr.isV6() && storage_.addr.asV6().isLinkLocal());
118  } else if (external_) {
119  // Unix addresses are always local to a host. Return true,
120  // since this conforms to the semantics of returning true for IP loopback
121  // addresses.
122  return true;
123  }
124  return false;
125 }
sa_family_t getFamily() const
union folly::SocketAddress::AddrStorage storage_
static SocketAddress folly::SocketAddress::makeFromPath ( StringPiece  path)
inlinestatic

Construct a SocketAddress from a local unix socket path.

Raises std::invalid_argument on error.

Parameters
pathThe Unix domain socket path.

Definition at line 317 of file SocketAddress.h.

References addr, setFromLocalAddress(), setFromPath(), setFromPeerAddress(), setFromSockaddr(), and folly::netops::socket().

317  {
319  addr.setFromPath(path);
320  return addr;
321  }
ThreadPoolListHook * addr
bool folly::SocketAddress::mapToIPv6 ( )

Convert an IPv4 address to IPv6 [::ffff:a.b.c.d]

Definition at line 447 of file SocketAddress.cpp.

Referenced by isIPv4Mapped().

447  {
448  if (getFamily() != AF_INET) {
449  return false;
450  }
451 
452  storage_.addr = folly::IPAddress::createIPv6(storage_.addr);
453  return true;
454 }
sa_family_t getFamily() const
union folly::SocketAddress::AddrStorage storage_
bool folly::SocketAddress::operator!= ( const SocketAddress other) const
inline

Definition at line 522 of file SocketAddress.h.

References hash(), operator<(), and prefixMatch().

522  {
523  return !(*this == other);
524  }
bool folly::SocketAddress::operator< ( const SocketAddress other) const

Use this operator for storing maps based on SocketAddress.

Definition at line 725 of file SocketAddress.cpp.

References folly::SocketAddress::ExternalUnixAddr::addr, folly::SocketAddress::AddrStorage::addr, getFamily(), folly::SocketAddress::ExternalUnixAddr::pathLength(), port_, storage_, and folly::SocketAddress::AddrStorage::un.

Referenced by operator!=().

725  {
726  if (getFamily() != other.getFamily()) {
727  return getFamily() < other.getFamily();
728  }
729 
730  if (external_) {
731  // Anonymous addresses can't be compared to anything else.
732  // Return that they are never less than anything.
733  //
734  // Note that this still meets the requirements for a strict weak
735  // ordering, so we can use this operator<() with standard C++ containers.
736  auto thisPathLength = storage_.un.pathLength();
737  if (thisPathLength == 0) {
738  return false;
739  }
740  auto otherPathLength = other.storage_.un.pathLength();
741  if (otherPathLength == 0) {
742  return true;
743  }
744 
745  // Compare based on path length first, for efficiency
746  if (thisPathLength != otherPathLength) {
747  return thisPathLength < otherPathLength;
748  }
749  int cmp = memcmp(
750  storage_.un.addr->sun_path,
751  other.storage_.un.addr->sun_path,
752  size_t(thisPathLength));
753  return cmp < 0;
754  }
755  switch (getFamily()) {
756  case AF_INET:
757  case AF_INET6: {
758  if (port_ != other.port_) {
759  return port_ < other.port_;
760  }
761 
762  return storage_.addr < other.storage_.addr;
763  }
764  case AF_UNSPEC:
765  default:
766  throw std::invalid_argument(
767  "SocketAddress: unsupported address family for comparing");
768  }
769 }
sa_family_t getFamily() const
union folly::SocketAddress::AddrStorage storage_
SocketAddress& folly::SocketAddress::operator= ( const SocketAddress addr)
inline

Definition at line 90 of file SocketAddress.h.

References folly::SocketAddress::ExternalUnixAddr::copy(), external_, folly::SocketAddress::ExternalUnixAddr::free(), getFamily(), folly::SocketAddress::ExternalUnixAddr::init(), port_, storage_, and folly::SocketAddress::AddrStorage::un.

90  {
91  if (!external_) {
92  if (addr.getFamily() != AF_UNIX) {
93  storage_ = addr.storage_;
94  } else {
95  storage_ = addr.storage_;
96  storage_.un.init(addr.storage_.un);
97  }
98  } else {
99  if (addr.getFamily() == AF_UNIX) {
100  storage_.un.copy(addr.storage_.un);
101  } else {
102  storage_.un.free();
103  storage_ = addr.storage_;
104  }
105  }
106  port_ = addr.port_;
107  external_ = addr.external_;
108  return *this;
109  }
void copy(const ExternalUnixAddr &other)
union folly::SocketAddress::AddrStorage storage_
ThreadPoolListHook * addr
SocketAddress& folly::SocketAddress::operator= ( SocketAddress &&  addr)
inline

Definition at line 118 of file SocketAddress.h.

References addr, external_, port_, storage_, and folly::f14::swap().

118  {
119  std::swap(storage_, addr.storage_);
120  std::swap(port_, addr.port_);
121  std::swap(external_, addr.external_);
122  return *this;
123  }
union folly::SocketAddress::AddrStorage storage_
void swap(SwapTrackingAlloc< T > &, SwapTrackingAlloc< T > &)
Definition: F14TestUtil.h:414
ThreadPoolListHook * addr
bool folly::SocketAddress::operator== ( const SocketAddress other) const

Definition at line 523 of file SocketAddress.cpp.

References folly::SocketAddress::ExternalUnixAddr::addr, folly::SocketAddress::AddrStorage::addr, external_, getFamily(), folly::SocketAddress::ExternalUnixAddr::len, folly::SocketAddress::ExternalUnixAddr::pathLength(), port_, storage_, and folly::SocketAddress::AddrStorage::un.

Referenced by isIPv4Mapped().

523  {
524  if (external_ != other.external_ || other.getFamily() != getFamily()) {
525  return false;
526  }
527  if (external_) {
528  // anonymous addresses are never equal to any other addresses
529  if (storage_.un.pathLength() == 0 || other.storage_.un.pathLength() == 0) {
530  return false;
531  }
532 
533  if (storage_.un.len != other.storage_.un.len) {
534  return false;
535  }
536  int cmp = memcmp(
537  storage_.un.addr->sun_path,
538  other.storage_.un.addr->sun_path,
539  size_t(storage_.un.pathLength()));
540  return cmp == 0;
541  }
542 
543  switch (getFamily()) {
544  case AF_INET:
545  case AF_INET6:
546  return (other.storage_.addr == storage_.addr) && (other.port_ == port_);
547  default:
548  throw std::invalid_argument(
549  "SocketAddress: unsupported address family "
550  "for comparison");
551  }
552 }
sa_family_t getFamily() const
union folly::SocketAddress::AddrStorage storage_
bool folly::SocketAddress::prefixMatch ( const SocketAddress other,
unsigned  prefixLength 
) const

Check whether the first N bits of this address match the first N bits of another address.

Note
returns false if the addresses are not from the same address family or if the family is neither IPv4 nor IPv6

Definition at line 554 of file SocketAddress.cpp.

References folly::SocketAddress::AddrStorage::addr, FOLLY_FALLTHROUGH, getFamily(), prefix(), storage_, and uint8_t.

Referenced by CheckPrefixMatch(), wangle::NetworkAddress::contains(), operator!=(), and TEST().

556  {
557  if (other.getFamily() != getFamily()) {
558  return false;
559  }
560  uint8_t mask_length = 128;
561  switch (getFamily()) {
562  case AF_INET:
563  mask_length = 32;
565  case AF_INET6: {
566  auto prefix = folly::IPAddress::longestCommonPrefix(
567  {storage_.addr, mask_length}, {other.storage_.addr, mask_length});
568  return prefix.second >= prefixLength;
569  }
570  default:
571  return false;
572  }
573 }
bool prefix(Cursor &c, uint32_t expected)
sa_family_t getFamily() const
union folly::SocketAddress::AddrStorage storage_
#define FOLLY_FALLTHROUGH
Definition: CppAttributes.h:63
void folly::SocketAddress::reset ( )
inline
void folly::SocketAddress::setFromAddrInfo ( const struct addrinfo *  results)
private

Definition at line 639 of file SocketAddress.cpp.

Referenced by folly::SocketAddress::ExternalUnixAddr::free().

639  {
640  setFromSockaddr(info->ai_addr, socklen_t(info->ai_addrlen));
641 }
def info()
Definition: deadlock.py:447
void setFromSockaddr(const struct sockaddr *address)
void folly::SocketAddress::setFromHostPort ( const char *  host,
uint16_t  port 
)

Initialize this SocketAddress from a hostname and port.

Note: If the host parameter is not a numeric IP address, hostname resolution will be performed, which can be quite slow.

If the hostname resolves to multiple addresses, only the first will be returned.

Raises std::system_error on error.

Parameters
hostThe hostname or IP address
portThe port (in host byte order)

Definition at line 138 of file SocketAddress.cpp.

Referenced by main(), reset(), setFromHostPort(), setFromIpPort(), SocketAddress(), and TEST().

138  {
139  ScopedAddrInfo results(getAddrInfo(host, port, 0));
140  setFromAddrInfo(results.info);
141 }
void setFromAddrInfo(const struct addrinfo *results)
struct addrinfo * getAddrInfo(const char *host, uint16_t port, int flags)
void folly::SocketAddress::setFromHostPort ( const std::string host,
uint16_t  port 
)
inline

Definition at line 179 of file SocketAddress.h.

References setFromHostPort(), setFromIpPort(), and uint16_t.

179  {
180  setFromHostPort(host.c_str(), port);
181  }
void setFromHostPort(const char *host, uint16_t port)
void folly::SocketAddress::setFromHostPort ( const char *  hostAndPort)

Initialize this SocketAddress from a host name and port number.

The addressAndPort string must be of the form "<host>:<port>". E.g., "www.facebook.com:443".

If the host name is not a numeric IP address, a DNS lookup will be performed. Beware that the DNS lookup may be very slow. The port number must be numeric; non-numeric service port names are not accepted.

Definition at line 180 of file SocketAddress.cpp.

180  {
181  HostAndPort hp(hostAndPort, true);
182  ScopedAddrInfo results(getAddrInfo(hp.host, hp.port, 0));
183  setFromAddrInfo(results.info);
184 }
void setFromAddrInfo(const struct addrinfo *results)
struct addrinfo * getAddrInfo(const char *host, uint16_t port, int flags)
void folly::SocketAddress::setFromHostPort ( const std::string hostAndPort)
inline

Definition at line 276 of file SocketAddress.h.

References getFamilyNameFrom(), getPortFrom(), setFromHostPort(), and setFromPath().

276  {
277  return setFromHostPort(hostAndPort.c_str());
278  }
void setFromHostPort(const char *host, uint16_t port)
void folly::SocketAddress::setFromIpAddrPort ( const IPAddress &  ip,
uint16_t  port 
)

Initialize this SocketAddress from an IPAddress struct and port.

Parameters
ipThe IP address in IPAddress format
portThe port (in host byte order)

Definition at line 148 of file SocketAddress.cpp.

Referenced by setFromIpPort(), SocketAddress(), and TEST().

148  {
149  if (external_) {
150  storage_.un.free();
151  external_ = false;
152  }
153  storage_.addr = ipAddr;
154  port_ = port;
155 }
union folly::SocketAddress::AddrStorage storage_
void folly::SocketAddress::setFromIpPort ( const char *  ip,
uint16_t  port 
)

Initialize this SocketAddress from an IP address and port.

This is similar to setFromHostPort(), but only accepts numeric IP addresses. If the IP string does not look like an IP address, it throws a std::invalid_argument rather than trying to perform a hostname resolution.

Raises std::system_error on error.

Parameters
ipThe IP address, as a human-readable string.
portThe port (in host byte order)

Definition at line 143 of file SocketAddress.cpp.

Referenced by TestAsyncTransport::getLocalAddress(), TestAsyncTransport::getPeerAddress(), setFromHostPort(), setFromIpPort(), setFromLocalIpPort(), SocketAddress(), and TEST().

143  {
144  ScopedAddrInfo results(getAddrInfo(ip, port, AI_NUMERICHOST));
145  setFromAddrInfo(results.info);
146 }
void setFromAddrInfo(const struct addrinfo *results)
struct addrinfo * getAddrInfo(const char *host, uint16_t port, int flags)
void folly::SocketAddress::setFromIpPort ( const std::string ip,
uint16_t  port 
)
inline

Definition at line 197 of file SocketAddress.h.

References setFromIpAddrPort(), setFromIpPort(), setFromLocalPort(), and uint16_t.

197  {
198  setFromIpPort(ip.c_str(), port);
199  }
void setFromIpPort(const char *ip, uint16_t port)
void folly::SocketAddress::setFromIpPort ( const char *  addressAndPort)

Initialize this SocketAddress from an IP address and port number.

The addressAndPort string must be of the form "<ip>:<port>". E.g., "10.0.0.1:1234".

Both the IP address and port number must be numeric. DNS host names and non-numeric service port names are not accepted.

Definition at line 174 of file SocketAddress.cpp.

174  {
175  HostAndPort hp(addressAndPort, true);
176  ScopedAddrInfo results(getAddrInfo(hp.host, hp.port, AI_NUMERICHOST));
177  setFromAddrInfo(results.info);
178 }
void setFromAddrInfo(const struct addrinfo *results)
struct addrinfo * getAddrInfo(const char *host, uint16_t port, int flags)
void folly::SocketAddress::setFromIpPort ( const std::string addressAndPort)
inline

Definition at line 261 of file SocketAddress.h.

References setFromHostPort(), and setFromIpPort().

261  {
262  return setFromIpPort(addressAndPort.c_str());
263  }
void setFromIpPort(const char *ip, uint16_t port)
void folly::SocketAddress::setFromLocalAddr ( const struct addrinfo *  results)
private

Definition at line 643 of file SocketAddress.cpp.

Referenced by folly::SocketAddress::ExternalUnixAddr::free().

643  {
644  // If an IPv6 address is present, prefer to use it, since IPv4 addresses
645  // can be mapped into IPv6 space.
646  for (const struct addrinfo* ai = info; ai != nullptr; ai = ai->ai_next) {
647  if (ai->ai_family == AF_INET6) {
648  setFromSockaddr(ai->ai_addr, socklen_t(ai->ai_addrlen));
649  return;
650  }
651  }
652 
653  // Otherwise, just use the first address in the list.
654  setFromSockaddr(info->ai_addr, socklen_t(info->ai_addrlen));
655 }
def info()
Definition: deadlock.py:447
void setFromSockaddr(const struct sockaddr *address)
void folly::SocketAddress::setFromLocalAddress ( int  socket)
void folly::SocketAddress::setFromLocalAddress ( NetworkSocket  socket)

Definition at line 257 of file SocketAddress.cpp.

References folly::netops::getsockname().

257  {
259 }
int getsockname(NetworkSocket s, sockaddr *name, socklen_t *namelen)
Definition: NetOps.cpp:108
NetworkSocket socket(int af, int type, int protocol)
Definition: NetOps.cpp:412
void setFromSocket(NetworkSocket socket, int(*fn)(NetworkSocket, struct sockaddr *, socklen_t *))
void folly::SocketAddress::setFromLocalIpPort ( const char *  addressAndPort)

Initialize this SocketAddress from a local port number and optional IP address.

The addressAndPort string may be specified either as "<ip>:<port>", or just as "<port>". If the IP is not specified, the address will be initialized to 0, so that a server socket bound to this address will accept connections on all local IP addresses.

Both the IP address and port number must be numeric. DNS host names and non-numeric service port names are not accepted.

Definition at line 167 of file SocketAddress.cpp.

Referenced by setFromLocalIpPort(), setFromLocalPort(), and TEST().

167  {
168  HostAndPort hp(addressAndPort, false);
169  ScopedAddrInfo results(
170  getAddrInfo(hp.host, hp.port, AI_NUMERICHOST | AI_ADDRCONFIG));
171  setFromLocalAddr(results.info);
172 }
struct addrinfo * getAddrInfo(const char *host, uint16_t port, int flags)
void setFromLocalAddr(const struct addrinfo *results)
void folly::SocketAddress::setFromLocalIpPort ( const std::string addressAndPort)
inline

Definition at line 247 of file SocketAddress.h.

References setFromIpPort(), and setFromLocalIpPort().

247  {
248  return setFromLocalIpPort(addressAndPort.c_str());
249  }
void setFromLocalIpPort(const char *addressAndPort)
void folly::SocketAddress::setFromLocalPort ( uint16_t  port)

Initialize this SocketAddress from a local port number.

This is intended to be used by server code to determine the address to listen on.

If the current machine has any IPv6 addresses configured, an IPv6 address will be returned (since connections from IPv4 clients can be mapped to the IPv6 address). If the machine does not have any IPv6 addresses, an IPv4 address will be returned.

Definition at line 157 of file SocketAddress.cpp.

Referenced by wangle::ServerBootstrap< DefaultPipeline >::bind(), SimpleServerPool::connect(), proxygen::ScopedHTTPServer::start< std::unique_ptr< RequestHandlerFactory > >(), setFromIpPort(), setFromLocalPort(), and TEST().

157  {
158  ScopedAddrInfo results(getAddrInfo(nullptr, port, AI_ADDRCONFIG));
159  setFromLocalAddr(results.info);
160 }
struct addrinfo * getAddrInfo(const char *host, uint16_t port, int flags)
void setFromLocalAddr(const struct addrinfo *results)
void folly::SocketAddress::setFromLocalPort ( const char *  port)

Initialize this SocketAddress from a local port number.

This version of setFromLocalPort() accepts the port as a string. A std::invalid_argument will be raised if the string does not refer to a port number. Non-numeric service port names are not accepted.

Definition at line 162 of file SocketAddress.cpp.

162  {
163  ScopedAddrInfo results(getAddrInfo(nullptr, port, AI_ADDRCONFIG));
164  setFromLocalAddr(results.info);
165 }
struct addrinfo * getAddrInfo(const char *host, uint16_t port, int flags)
void setFromLocalAddr(const struct addrinfo *results)
void folly::SocketAddress::setFromLocalPort ( const std::string port)
inline

Definition at line 230 of file SocketAddress.h.

References setFromLocalIpPort(), and setFromLocalPort().

230  {
231  return setFromLocalPort(port.c_str());
232  }
void setFromLocalPort(uint16_t port)
void folly::SocketAddress::setFromPath ( StringPiece  path)

Initialize this SocketAddress from a local unix path.

Raises std::invalid_argument on error.

Definition at line 219 of file SocketAddress.cpp.

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

Referenced by makeFromPath(), setFromHostPort(), setFromPath(), and TEST().

219  {
220  // Before we touch storage_, check to see if the length is too big.
221  // Note that "storage_.un.addr->sun_path" may not be safe to evaluate here,
222  // but sizeof() just uses its type, and does't evaluate it.
223  if (path.size() > sizeof(storage_.un.addr->sun_path)) {
224  throw std::invalid_argument(
225  "socket path too large to fit into sockaddr_un");
226  }
227 
228  if (!external_) {
229  storage_.un.init();
230  external_ = true;
231  }
232 
233  size_t len = path.size();
234  storage_.un.len = socklen_t(offsetof(struct sockaddr_un, sun_path) + len);
235  memcpy(storage_.un.addr->sun_path, path.data(), len);
236  // If there is room, put a terminating NUL byte in sun_path. In general the
237  // path should be NUL terminated, although getsockname() and getpeername()
238  // may return Unix socket addresses with paths that fit exactly in sun_path
239  // with no terminating NUL.
240  if (len < sizeof(storage_.un.addr->sun_path)) {
241  storage_.un.addr->sun_path[len] = '\0';
242  }
243 }
union folly::SocketAddress::AddrStorage storage_
void folly::SocketAddress::setFromPath ( const char *  path,
size_t  length 
)
inline

Definition at line 306 of file SocketAddress.h.

References setFromPath().

306  {
307  setFromPath(StringPiece{path, length});
308  }
void setFromPath(StringPiece path)
Range< const char * > StringPiece
void folly::SocketAddress::setFromPeerAddress ( int  socket)

Initialize this SocketAddress from a socket's peer address.

Raises std::system_error on error.

Definition at line 245 of file SocketAddress.cpp.

Referenced by folly::AsyncSocket::cachePeerAddress(), makeFromPath(), TEST(), and testSetFromSocket().

245  {
247 }
void setFromPeerAddress(int socket)
NetworkSocket socket(int af, int type, int protocol)
Definition: NetOps.cpp:412
static NetworkSocket fromFd(int fd)
Definition: NetworkSocket.h:44
void folly::SocketAddress::setFromPeerAddress ( NetworkSocket  socket)

Definition at line 249 of file SocketAddress.cpp.

References folly::netops::getpeername().

249  {
251 }
NetworkSocket socket(int af, int type, int protocol)
Definition: NetOps.cpp:412
void setFromSocket(NetworkSocket socket, int(*fn)(NetworkSocket, struct sockaddr *, socklen_t *))
int getpeername(NetworkSocket s, sockaddr *name, socklen_t *namelen)
Definition: NetOps.cpp:104
void folly::SocketAddress::setFromSockaddr ( const struct sockaddr *  address)

Initialize this folly::SocketAddress from a struct sockaddr.

Raises std::system_error on error.

This method is not supported for AF_UNIX addresses. For unix addresses, the address length must be explicitly specified.

Parameters
addressA struct sockaddr. The size of the address is implied from address->sa_family.

Definition at line 261 of file SocketAddress.cpp.

References uint16_t.

Referenced by folly::AsyncUDPSocket::handleRead(), folly::AsyncServerSocket::handlerReady(), makeFromPath(), and testSetFromSocket().

261  {
262  uint16_t port;
263 
264  if (address->sa_family == AF_INET) {
265  port = ntohs(((sockaddr_in*)address)->sin_port);
266  } else if (address->sa_family == AF_INET6) {
267  port = ntohs(((sockaddr_in6*)address)->sin6_port);
268  } else if (address->sa_family == AF_UNIX) {
269  // We need an explicitly specified length for AF_UNIX addresses,
270  // to be able to distinguish anonymous addresses from addresses
271  // in Linux's abstract namespace.
272  throw std::invalid_argument(
273  "SocketAddress::setFromSockaddr(): the address "
274  "length must be explicitly specified when "
275  "setting AF_UNIX addresses");
276  } else {
277  throw std::invalid_argument(
278  "SocketAddress::setFromSockaddr() called "
279  "with unsupported address type");
280  }
281 
282  setFromIpAddrPort(folly::IPAddress(address), port);
283 }
void setFromIpAddrPort(const IPAddress &ip, uint16_t port)
void folly::SocketAddress::setFromSockaddr ( const struct sockaddr *  address,
socklen_t  addrlen 
)

Initialize this SocketAddress from a struct sockaddr.

Raises std::system_error on error.

Parameters
addressA struct sockaddr.
addrlenThe length of address data available. This must be long enough for the full address type required by address->sa_family.

Definition at line 285 of file SocketAddress.cpp.

287  {
288  // Check the length to make sure we can access address->sa_family
289  if (addrlen <
290  (offsetof(struct sockaddr, sa_family) + sizeof(address->sa_family))) {
291  throw std::invalid_argument(
292  "SocketAddress::setFromSockaddr() called "
293  "with length too short for a sockaddr");
294  }
295 
296  if (address->sa_family == AF_INET) {
297  if (addrlen < sizeof(struct sockaddr_in)) {
298  throw std::invalid_argument(
299  "SocketAddress::setFromSockaddr() called "
300  "with length too short for a sockaddr_in");
301  }
302  setFromSockaddr(reinterpret_cast<const struct sockaddr_in*>(address));
303  } else if (address->sa_family == AF_INET6) {
304  if (addrlen < sizeof(struct sockaddr_in6)) {
305  throw std::invalid_argument(
306  "SocketAddress::setFromSockaddr() called "
307  "with length too short for a sockaddr_in6");
308  }
309  setFromSockaddr(reinterpret_cast<const struct sockaddr_in6*>(address));
310  } else if (address->sa_family == AF_UNIX) {
312  reinterpret_cast<const struct sockaddr_un*>(address), addrlen);
313  } else {
314  throw std::invalid_argument(
315  "SocketAddress::setFromSockaddr() called "
316  "with unsupported address type");
317  }
318 }
void setFromSockaddr(const struct sockaddr *address)
void folly::SocketAddress::setFromSockaddr ( const struct sockaddr_in *  address)

Initialize this SocketAddress from a struct sockaddr_in.

Definition at line 320 of file SocketAddress.cpp.

320  {
321  assert(address->sin_family == AF_INET);
322  setFromSockaddr((sockaddr*)address);
323 }
void setFromSockaddr(const struct sockaddr *address)
void folly::SocketAddress::setFromSockaddr ( const struct sockaddr_in6 *  address)

Initialize this SocketAddress from a struct sockaddr_in6.

Definition at line 325 of file SocketAddress.cpp.

325  {
326  assert(address->sin6_family == AF_INET6);
327  setFromSockaddr((sockaddr*)address);
328 }
void setFromSockaddr(const struct sockaddr *address)
void folly::SocketAddress::setFromSockaddr ( const struct sockaddr_un *  address,
socklen_t  addrlen 
)

Initialize this SocketAddress from a struct sockaddr_un.

Note that the addrlen parameter is necessary to properly detect anonymous addresses, which have 0 valid path bytes, and may not even have a NUL character at the start of the path.

Parameters
addressA struct sockaddr_un.
addrlenThe length of address data. This should include all of the valid bytes of sun_path, not including any NUL terminator.

Definition at line 330 of file SocketAddress.cpp.

332  {
333  assert(address->sun_family == AF_UNIX);
334  if (addrlen > sizeof(struct sockaddr_un)) {
335  throw std::invalid_argument(
336  "SocketAddress::setFromSockaddr() called "
337  "with length too long for a sockaddr_un");
338  }
339 
340  if (!external_) {
341  storage_.un.init();
342  }
343  external_ = true;
344  memcpy(storage_.un.addr, address, size_t(addrlen));
345  updateUnixAddressLength(addrlen);
346 
347  // Fill the rest with 0s, just for safety
348  if (addrlen < sizeof(struct sockaddr_un)) {
349  char* p = reinterpret_cast<char*>(storage_.un.addr);
350  memset(p + addrlen, 0, sizeof(struct sockaddr_un) - addrlen);
351  }
352 }
void updateUnixAddressLength(socklen_t addrlen)
union folly::SocketAddress::AddrStorage storage_
void folly::SocketAddress::setFromSocket ( NetworkSocket  socket,
int(*)(NetworkSocket, struct sockaddr *, socklen_t *)  fn 
)
private

Definition at line 657 of file SocketAddress.cpp.

References folly::throwSystemError().

Referenced by folly::SocketAddress::ExternalUnixAddr::free().

659  {
660  // Try to put the address into a local storage buffer.
661  sockaddr_storage tmp_sock;
662  socklen_t addrLen = sizeof(tmp_sock);
663  if (fn(socket, (sockaddr*)&tmp_sock, &addrLen) != 0) {
664  folly::throwSystemError("setFromSocket() failed");
665  }
666 
667  setFromSockaddr((sockaddr*)&tmp_sock, addrLen);
668 }
void setFromSockaddr(const struct sockaddr *address)
NetworkSocket socket(int af, int type, int protocol)
Definition: NetOps.cpp:412
void throwSystemError(Args &&...args)
Definition: Exception.h:76
void folly::SocketAddress::setPort ( uint16_t  port)

Set the IPv4 or IPv6 port for this address.

Raises std::invalid_argument if this is not an IPv4 or IPv6 address.

Definition at line 417 of file SocketAddress.cpp.

Referenced by empty(), and TEST().

417  {
418  switch (getFamily()) {
419  case AF_INET:
420  case AF_INET6:
421  port_ = port;
422  return;
423  default:
424  throw std::invalid_argument(
425  "SocketAddress::setPort() called on non-IP "
426  "address");
427  }
428 }
sa_family_t getFamily() const
bool folly::SocketAddress::tryConvertToIPv4 ( )

Try to convert an address to IPv4.

This attempts to convert an address to an IPv4 address if possible. If the address is an IPv4-mapped IPv6 address, it is converted to an IPv4 address and true is returned. Otherwise nothing is done, and false is returned.

Definition at line 438 of file SocketAddress.cpp.

Referenced by proxygen::HTTPSessionBase::HTTPSessionBase(), and isIPv4Mapped().

438  {
439  if (!isIPv4Mapped()) {
440  return false;
441  }
442 
443  storage_.addr = folly::IPAddress::createIPv4(storage_.addr);
444  return true;
445 }
bool isIPv4Mapped() const
union folly::SocketAddress::AddrStorage storage_
void folly::SocketAddress::updateUnixAddressLength ( socklen_t  addrlen)
private

Definition at line 701 of file SocketAddress.cpp.

Referenced by folly::SocketAddress::ExternalUnixAddr::free().

701  {
702  if (addrlen < offsetof(struct sockaddr_un, sun_path)) {
703  throw std::invalid_argument(
704  "SocketAddress: attempted to set a Unix socket "
705  "with a length too short for a sockaddr_un");
706  }
707 
708  storage_.un.len = addrlen;
709  if (storage_.un.pathLength() == 0) {
710  // anonymous address
711  return;
712  }
713 
714  if (storage_.un.addr->sun_path[0] == '\0') {
715  // abstract namespace. honor the specified length
716  } else {
717  // Call strnlen(), just in case the length was overspecified.
718  size_t maxLength = addrlen - offsetof(struct sockaddr_un, sun_path);
719  size_t pathLength = strnlen(storage_.un.addr->sun_path, maxLength);
720  storage_.un.len =
721  socklen_t(offsetof(struct sockaddr_un, sun_path) + pathLength);
722  }
723 }
union folly::SocketAddress::AddrStorage storage_

Member Data Documentation

bool folly::SocketAddress::external_ {false}
private
uint16_t folly::SocketAddress::port_
private

Definition at line 607 of file SocketAddress.h.

Referenced by getAddress(), operator<(), operator=(), operator==(), and SocketAddress().


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