InetAddress.h revision 24ca08a8
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> 8efbfdb0cSShuo Chen 9efbfdb0cSShuo Chenclass InetAddress : copyable 10efbfdb0cSShuo Chen{ 11efbfdb0cSShuo Chen public: 1224ca08a8SShuo Chen // Invalid address 1324ca08a8SShuo Chen InetAddress() { addr_.sin_family = AF_UNSPEC; } 1424ca08a8SShuo Chen // for connecting 15d47c0202SShuo Chen InetAddress(StringArg ip, uint16_t port); 1624ca08a8SShuo Chen // for listening 1724ca08a8SShuo Chen explicit InetAddress(uint16_t port, bool ipv6 = false); 1824ca08a8SShuo Chen // interface with Sockets API 1924ca08a8SShuo Chen explicit InetAddress(const struct sockaddr& saddr); 20efbfdb0cSShuo Chen 21efbfdb0cSShuo Chen // default copy/assignment are Okay 22efbfdb0cSShuo Chen 2324ca08a8SShuo Chen sa_family_t family() const { return addr_.sin_family; } 2424ca08a8SShuo Chen uint16_t port() const { return ntohs(addr_.sin_port); } 2524ca08a8SShuo Chen void setPort(uint16_t port) { addr_.sin_port = htons(port); } 2624ca08a8SShuo Chen 275b543c9cSShuo Chen std::string toIp() const; 285b543c9cSShuo Chen std::string toIpPort() const; 29efbfdb0cSShuo Chen 3024ca08a8SShuo Chen // Interface with Sockets API 3124ca08a8SShuo Chen const struct sockaddr* get_sockaddr() const 3224ca08a8SShuo Chen { 3324ca08a8SShuo Chen return reinterpret_cast<const struct sockaddr*>(&addr6_); 3424ca08a8SShuo Chen } 355b543c9cSShuo Chen 3624ca08a8SShuo Chen socklen_t length() const 3724ca08a8SShuo Chen { 3824ca08a8SShuo Chen // TODO: switch (family()) 3924ca08a8SShuo Chen return sizeof addr6_; 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