Sponge
CS144's user-space TCP library
address.hh
Go to the documentation of this file.
1 #ifndef SPONGE_LIBSPONGE_ADDRESS_HH
2 #define SPONGE_LIBSPONGE_ADDRESS_HH
3 
4 #include <cstddef>
5 #include <cstdint>
6 #include <netdb.h>
7 #include <netinet/in.h>
8 #include <string>
9 #include <sys/socket.h>
10 #include <utility>
11 
13 class Address {
14  public:
17  class Raw {
18  public:
19  sockaddr_storage storage{};
20  operator sockaddr *();
21  operator const sockaddr *() const;
22  };
23 
24  private:
25  socklen_t _size;
27 
29  Address(const std::string &node, const std::string &service, const addrinfo &hints);
30 
31  public:
33  Address(const std::string &hostname, const std::string &service);
34 
36  Address(const std::string &ip, const std::uint16_t port = 0);
37 
39  Address(const sockaddr *addr, const std::size_t size);
40 
42  bool operator==(const Address &other) const;
43  bool operator!=(const Address &other) const { return not operator==(other); }
44 
47 
51  std::string ip() const { return ip_port().first; }
53  uint16_t port() const { return ip_port().second; }
55  uint32_t ipv4_numeric() const;
57  static Address from_ipv4_numeric(const uint32_t ip_address);
59  std::string to_string() const;
61 
64 
66  socklen_t size() const { return _size; }
68  operator const sockaddr *() const { return _address; }
70 };
71 
84 
85 #endif // SPONGE_LIBSPONGE_ADDRESS_HH
Wrapper around sockaddr_storage.
Definition: address.hh:17
sockaddr_storage storage
The wrapped struct itself.
Definition: address.hh:19
Wrapper around IPv4 addresses and DNS operations.
Definition: address.hh:13
std::pair< std::string, uint16_t > ip_port() const
Dotted-quad IP address string ("18.243.0.1") and numeric port.
Definition: address.cc:90
socklen_t size() const
Size of the underlying address storage.
Definition: address.hh:66
bool operator==(const Address &other) const
Equality comparison.
Definition: address.cc:128
Address(const std::string &node, const std::string &service, const addrinfo &hints)
Constructor from ip/host, service/port, and hints to the resolver.
Definition: address.cc:45
std::string to_string() const
Human-readable string, e.g., "8.8.8.8:53".
Definition: address.cc:103
uint32_t ipv4_numeric() const
Numeric IP address as an integer (i.e., in host byte order).
Definition: address.cc:108
static Address from_ipv4_numeric(const uint32_t ip_address)
Create an Address from a 32-bit raw numeric IP address.
Definition: address.cc:119
socklen_t _size
Size of the wrapped address.
Definition: address.hh:25
uint16_t port() const
Numeric port (host byte order).
Definition: address.hh:53
std::string ip() const
Dotted-quad IP address string ("18.243.0.1").
Definition: address.hh:51
bool operator!=(const Address &other) const
Definition: address.hh:43
Raw _address
A wrapped sockaddr_storage containing the address.
Definition: address.hh:26