1efbfdb0cSShuo Chen#pragma once
2efbfdb0cSShuo Chen#include "Common.h"
3efbfdb0cSShuo Chen
4efbfdb0cSShuo Chen#include <string>
55b543c9cSShuo Chen#include <vector>
6efbfdb0cSShuo Chen
7efbfdb0cSShuo Chen#include <netinet/in.h>
8e146b157SShuo Chen#include <sys/socket.h>
9efbfdb0cSShuo Chen
10efbfdb0cSShuo Chenclass InetAddress : copyable
11efbfdb0cSShuo Chen{
12efbfdb0cSShuo Chen public:
1324ca08a8SShuo Chen  // Invalid address
1424ca08a8SShuo Chen  InetAddress() { addr_.sin_family = AF_UNSPEC; }
1524ca08a8SShuo Chen  // for connecting
16d47c0202SShuo Chen  InetAddress(StringArg ip, uint16_t port);
1724ca08a8SShuo Chen  // for listening
1824ca08a8SShuo Chen  explicit InetAddress(uint16_t port, bool ipv6 = false);
1924ca08a8SShuo Chen  // interface with Sockets API
2024ca08a8SShuo Chen  explicit InetAddress(const struct sockaddr& saddr);
21efbfdb0cSShuo Chen
22efbfdb0cSShuo Chen  // default copy/assignment are Okay
23efbfdb0cSShuo Chen
2424ca08a8SShuo Chen  sa_family_t family() const { return addr_.sin_family; }
2524ca08a8SShuo Chen  uint16_t port() const { return ntohs(addr_.sin_port); }
2624ca08a8SShuo Chen  void setPort(uint16_t port) { addr_.sin_port = htons(port); }
2724ca08a8SShuo Chen
285b543c9cSShuo Chen  std::string toIp() const;
295b543c9cSShuo Chen  std::string toIpPort() const;
30efbfdb0cSShuo Chen
3124ca08a8SShuo Chen  // Interface with Sockets API
3224ca08a8SShuo Chen  const struct sockaddr* get_sockaddr() const
3324ca08a8SShuo Chen  {
3424ca08a8SShuo Chen    return reinterpret_cast<const struct sockaddr*>(&addr6_);
3524ca08a8SShuo Chen  }
365b543c9cSShuo Chen
3724ca08a8SShuo Chen  socklen_t length() const
3824ca08a8SShuo Chen  {
39e146b157SShuo Chen    return family() == AF_INET6 ? sizeof addr6_ : sizeof addr_;
4024ca08a8SShuo Chen  }
41efbfdb0cSShuo Chen
4224ca08a8SShuo Chen  bool operator==(const InetAddress& rhs) const;
43355c2bf7SShuo Chen
4424ca08a8SShuo Chen  // Resolves hostname to IP address.
4524ca08a8SShuo Chen  // Returns true on success.
4624ca08a8SShuo Chen  // Thread safe.
4724ca08a8SShuo Chen  static bool resolve(StringArg hostname, uint16_t port, InetAddress*);
48aafef3ccSShuo Chen  static std::vector<InetAddress> resolveAll(StringArg hostname, uint16_t port = 0);
495b543c9cSShuo Chen
50efbfdb0cSShuo Chen private:
5124ca08a8SShuo Chen  union
5224ca08a8SShuo Chen  {
5324ca08a8SShuo Chen    struct sockaddr_in addr_;
5424ca08a8SShuo Chen    struct sockaddr_in6 addr6_;
5524ca08a8SShuo Chen  };
56efbfdb0cSShuo Chen};
57efbfdb0cSShuo Chen
58