Go to the documentation of this file.00001
00021 #ifndef HYPERTABLE_INETADDR_H
00022 #define HYPERTABLE_INETADDR_H
00023
00024 extern "C" {
00025 #include <netinet/in.h>
00026 }
00027
00028 #include "Common/String.h"
00029
00030 namespace Hypertable {
00031
00035 struct Endpoint {
00036 Endpoint(const String &host, uint16_t port) : host(host), port(port) {}
00037
00038 String host;
00039 uint16_t port;
00040 };
00041
00042 std::ostream &operator<<(std::ostream &, const Endpoint &);
00043
00050 struct InetAddr : sockaddr_in {
00051 InetAddr();
00052 InetAddr(const String &host, uint16_t port);
00053 InetAddr(const String &endpoint);
00054 InetAddr(uint32_t ip32, uint16_t port);
00055 InetAddr(const sockaddr_in &addr) { operator=(addr); }
00056
00057 size_t encoded_length() const;
00058 void encode(uint8_t **bufp) const;
00059 void decode(const uint8_t **bufp, size_t *remainp);
00060
00061 InetAddr &operator=(const sockaddr_in &addr) {
00062 if (this != &addr)
00063 memcpy(this, &addr, sizeof(sockaddr_in));
00064
00065 return *this;
00066 }
00067
00068 bool operator==(const InetAddr &other) const {
00069 return (bool)!memcmp(this, &other, sizeof(InetAddr));
00070 }
00071
00072 bool operator!=(const InetAddr &other) const {
00073 return !(*this == other);
00074 }
00075
00076 bool operator<(const InetAddr &other) const {
00077 if (sin_family != other.sin_family)
00078 return sin_family < other.sin_family;
00079 if (sin_addr.s_addr != other.sin_addr.s_addr)
00080 return sin_addr.s_addr < other.sin_addr.s_addr;
00081 return sin_port < other.sin_port;
00082 }
00083
00084 String format(int sep = ':') { return InetAddr::format(*this, sep); }
00085 String format_ipaddress() { return InetAddr::format_ipaddress(*this); }
00086 String hex(int sep = ':') { return InetAddr::hex(*this, sep); }
00087
00088
00090 static bool initialize(sockaddr_in *addr, const char *host, uint16_t port);
00091
00093 static bool initialize(sockaddr_in *addr, const char *addr_str);
00094
00102 static Endpoint parse_endpoint(const char *endpoint, int defport = 0);
00103 static Endpoint parse_endpoint(const String &endpoint, int defport = 0) {
00104 return parse_endpoint(endpoint.c_str(), defport);
00105 }
00106
00115 static bool parse_ipv4(const char *ip, uint16_t port, sockaddr_in &addr,
00116 int base = 0);
00117
00119 static bool initialize(sockaddr_in *addr, uint32_t haddr, uint16_t port);
00120
00122 static const char *string_format(String &addr_str, const sockaddr_in &addr);
00123 static String format(const sockaddr_in &addr, int sep = ':');
00124 static String format_ipaddress(const sockaddr_in &addr);
00125 static String hex(const sockaddr_in &addr, int sep = ':');
00126 };
00127
00128 std::ostream &operator<<(std::ostream &, const sockaddr_in &);
00129
00130 }
00131
00132 #endif // HYPERTABLE_INETADDR_H