sources/network/ipaddress.h

branch
protocol5
changeset 195
be953e1621d9
parent 190
90bf9049e5eb
--- a/sources/network/ipaddress.h	Wed Jan 27 12:41:50 2021 +0200
+++ b/sources/network/ipaddress.h	Wed Jan 27 19:48:41 2021 +0200
@@ -1,5 +1,5 @@
 /*
-	Copyright 2014 - 2016 Teemu Piippo
+	Copyright 2014 - 2021 Teemu Piippo
 	All rights reserved.
 
 	Redistribution and use in source and binary forms, with or without
@@ -29,6 +29,7 @@
 */
 
 #pragma once
+#include <ostream>
 #include "../main.h"
 
 struct sockaddr;
@@ -36,52 +37,27 @@
 
 BEGIN_ZFC_NAMESPACE
 
-struct IPAddress
+namespace net
 {
-	enum
-	{
-		LOCALHOST = 0x7f000001
-	};
-
-	enum WithPort
-	{
-		WITH_PORT,
-		NO_PORT
-	};
-
-	class StringParseError : public std::exception
+	using octet_t = std::uint8_t;
+	using port_t = std::uint16_t;
+	using host_t = std::uint32_t;
+	struct ip_address
 	{
-		String m_message;
-
-	public:
-		StringParseError (String message) :
-			m_message (message) {}
-
-		const char* what() const throw()
-		{
-			return m_message.chars();
-		}
+		net::host_t host = 0;
+		net::port_t port = 0;
+		bool operator<(const ip_address& other) const;
+		bool operator==(const ip_address& other) const;
 	};
-
-	unsigned long host;
-	unsigned short port;
-
-	IPAddress();
-	IPAddress (unsigned long host, unsigned short port);
-	IPAddress (const IPAddress& other);
-
-	bool compare (const IPAddress& other) const;
-	unsigned char octet (int n) const;
-	void set_octet (int n, unsigned char oct);
-	String to_string (WithPort withport = NO_PORT) const;
-	sockaddr_in to_sockaddr_in() const;
-	bool operator< (const IPAddress& other) const;
-	bool operator== (const IPAddress& other) const { return compare (other); }
-	bool operator!= (const IPAddress& other) const { return not compare (other); }
-	unsigned char operator[] (int n) const { return octet (n); }
-
-	static IPAddress from_string (String input);
-	static IPAddress resolve (String node);
-};
+	constexpr ip_address localhost = {0x7f000001, 0};
+	int ip_compare(const ip_address& one, const ip_address& other);
+	net::octet_t ip_octet(const ip_address& address, unsigned char n);
+	void ip_set_octet(ip_address* address, unsigned char n, net::octet_t octet);
+	std::optional<unsigned short> ip_parse_port(const char* port_string, std::ostream& errorStream);
+	std::optional<ip_address> ip_resolve_hostname(const std::string& node, std::ostream& errorStream);
+	std::optional<ip_address> ip_resolve(const std::string& input_string, std::ostream &errorStream);
+	sockaddr_in ip_address_to_sockaddr_in(const ip_address& address);
+	std::string ip_address_to_string(const ip_address& address);
+}
 
 END_ZFC_NAMESPACE

mercurial