sources/network/ipaddress.h

changeset 186
9330b93d9946
parent 184
afd63357a03d
child 188
5fc32e4b2a8c
equal deleted inserted replaced
185:e83ec58cc458 186:9330b93d9946
27 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */ 29 */
30 30
31 #pragma once 31 #pragma once
32 #include <ostream>
32 #include "../main.h" 33 #include "../main.h"
33 34
34 struct sockaddr; 35 struct sockaddr;
35 struct sockaddr_in; 36 struct sockaddr_in;
36 37
37 BEGIN_ZFC_NAMESPACE 38 BEGIN_ZFC_NAMESPACE
38 39
39 struct IPAddress 40 namespace net
40 { 41 {
41 enum 42 using octet_t = std::uint8_t;
43 struct ip_address
42 { 44 {
43 LOCALHOST = 0x7f000001 45 std::uint32_t host;
46 std::uint16_t port;
47 bool operator<(const ip_address& other) const;
48 bool operator==(const ip_address& other) const;
44 }; 49 };
45 50 constexpr ip_address localhost = {0x7f000001, 0};
46 enum WithPort 51 int ip_compare(const ip_address& one, const ip_address& other);
47 { 52 net::octet_t ip_octet(const ip_address& address, unsigned char n);
48 WITH_PORT, 53 void ip_set_octet(ip_address* address, unsigned char n, net::octet_t octet);
49 NO_PORT 54 std::optional<ip_address> ip_scan_octets(const char* address_string);
50 }; 55 std::optional<unsigned short> ip_parse_port(const char* port_string, std::ostream& errorStream);
51 56 std::optional<ip_address> ip_resolve_hostname(const std::string& node, std::ostream& errorStream);
52 class StringParseError : public std::exception 57 std::optional<ip_address> ip_resolve(const std::string& input_string, std::ostream &errorStream);
53 { 58 sockaddr_in ip_address_to_sockaddr_in(const ip_address& address);
54 std::string m_message; 59 std::string ip_address_to_string(const ip_address& address);
55 60 }
56 public:
57 StringParseError (std::string message) :
58 m_message (message) {}
59
60 const char* what() const throw()
61 {
62 return m_message.data();
63 }
64 };
65
66 unsigned long host;
67 unsigned short port;
68
69 bool compare (const IPAddress& other) const;
70 unsigned char octet (int n) const;
71 void set_octet (int n, unsigned char oct);
72 std::string to_string (WithPort withport = NO_PORT) const;
73 sockaddr_in to_sockaddr_in() const;
74 bool operator< (const IPAddress& other) const;
75 bool operator== (const IPAddress& other) const { return compare (other); }
76 bool operator!= (const IPAddress& other) const { return not compare (other); }
77 unsigned char operator[] (int n) const { return octet (n); }
78
79 static IPAddress from_string (std::string input);
80 static IPAddress resolve (std::string node);
81 };
82 61
83 END_ZFC_NAMESPACE 62 END_ZFC_NAMESPACE

mercurial