68 lines
1.7 KiB
C++
68 lines
1.7 KiB
C++
#pragma once
|
|
|
|
#if !defined(MIJIN_NET_IP_HPP_INCLUDED)
|
|
#define MIJIN_NET_IP_HPP_INCLUDED 1
|
|
|
|
#include <array>
|
|
#include <variant>
|
|
#include "../async/coroutine.hpp"
|
|
#include "../container/optional.hpp"
|
|
#include "../io/stream.hpp" // TODO: rename Stream{Error,Result} to IO{*}
|
|
|
|
namespace mijin
|
|
{
|
|
struct IPv4Address
|
|
{
|
|
std::array<std::uint8_t, 4> octets;
|
|
|
|
auto operator<=>(const IPv4Address&) const noexcept = default;
|
|
|
|
[[nodiscard]] std::string toString() const;
|
|
|
|
[[nodiscard]]
|
|
static Optional<IPv4Address> fromString(std::string_view stringView) noexcept;
|
|
};
|
|
|
|
struct IPv6Address
|
|
{
|
|
std::array<std::uint16_t, 8> hextets;
|
|
|
|
auto operator<=>(const IPv6Address&) const noexcept = default;
|
|
|
|
[[nodiscard]] std::string toString() const;
|
|
|
|
[[nodiscard]]
|
|
static Optional<IPv6Address> fromString(std::string_view stringView) noexcept;
|
|
};
|
|
using ip_address_t = std::variant<IPv4Address, IPv6Address>;
|
|
|
|
[[nodiscard]]
|
|
inline std::string ipAddressToString(const ip_address_t& address) noexcept
|
|
{
|
|
if (address.valueless_by_exception())
|
|
{
|
|
return "";
|
|
}
|
|
return std::visit([](const auto& addr) { return addr.toString(); }, address);
|
|
}
|
|
|
|
[[nodiscard]]
|
|
inline Optional<ip_address_t> ipAddressFromString(std::string_view stringView) noexcept
|
|
{
|
|
if (Optional<IPv4Address> ipv4Address = IPv4Address::fromString(stringView); !ipv4Address.empty())
|
|
{
|
|
return ip_address_t(*ipv4Address);
|
|
}
|
|
if (Optional<IPv6Address> ipv6Address = IPv6Address::fromString(stringView); !ipv6Address.empty())
|
|
{
|
|
return ip_address_t(*ipv6Address);
|
|
}
|
|
return NULL_OPTIONAL;
|
|
}
|
|
|
|
[[nodiscard]]
|
|
Task<StreamResult<std::vector<ip_address_t>>> c_resolveHostname(std::string hostname) noexcept;
|
|
}
|
|
|
|
#endif // !defined(MIJIN_NET_IP_HPP_INCLUDED)
|