1#pragma once 2#include "Common.h" 3 4#include <string> 5#include <vector> 6 7#include <netinet/in.h> 8#include <sys/socket.h> 9 10class InetAddress : copyable 11{ 12 public: 13 // Invalid address 14 InetAddress() { addr_.sin_family = AF_UNSPEC; } 15 // for connecting 16 InetAddress(StringArg ip, uint16_t port); 17 // for listening 18 explicit InetAddress(uint16_t port, bool ipv6 = false); 19 // interface with Sockets API 20 explicit InetAddress(const struct sockaddr& saddr); 21 22 // default copy/assignment are Okay 23 24 sa_family_t family() const { return addr_.sin_family; } 25 uint16_t port() const { return ntohs(addr_.sin_port); } 26 void setPort(uint16_t port) { addr_.sin_port = htons(port); } 27 28 std::string toIp() const; 29 std::string toIpPort() const; 30 31 // Interface with Sockets API 32 const struct sockaddr* get_sockaddr() const 33 { 34 return reinterpret_cast<const struct sockaddr*>(&addr6_); 35 } 36 37 socklen_t length() const 38 { 39 return family() == AF_INET6 ? sizeof addr6_ : sizeof addr_; 40 } 41 42 bool operator==(const InetAddress& rhs) const; 43 44 // Resolves hostname to IP address. 45 // Returns true on success. 46 // Thread safe. 47 static bool resolve(StringArg hostname, uint16_t port, InetAddress*); 48 static std::vector<InetAddress> resolveAll(StringArg hostname, uint16_t port = 0); 49 50 private: 51 union 52 { 53 struct sockaddr_in addr_; 54 struct sockaddr_in6 addr6_; 55 }; 56}; 57 58