Read "host:port", where the host is a name, an IPv4 address or a bracketed IPv6 address.
The split is at the last colon, so an IPv6 address must be bracketed: "[::1]:9000". The host is returned without its brackets. A host with a space or a control character, an empty host, or a missing or invalid port refuses the whole text.
58{
59 const size_t colon = text.rfind(':');
60 if (colon == std::string_view::npos) {
61 return std::nullopt;
62 }
63
64 std::string_view host = text.substr(0, colon);
65 const auto port =
parse_port(text.substr(colon + 1));
66 if (!port) {
67 return std::nullopt;
68 }
69
70 if (host.size() >= 2 && host.front() == '[' && host.back() == ']') {
71 host = host.substr(1, host.size() - 2);
72 } else if (host.find(':') != std::string_view::npos) {
73 return std::nullopt;
74 }
75
76 if (host.empty()) {
77 return std::nullopt;
78 }
79 for (const char c : host) {
80 if (static_cast<unsigned char>(c) <= ' ' || c == 0x7F) {
81 return std::nullopt;
82 }
83 }
84
85 return HostPort { .host = std::string(host), .port = *port };
86}
constexpr std::optional< uint16_t > parse_port(std::string_view text) noexcept
Read a port number, 1 to 65535.
A host and a port, as written in "host:port".