+namespace {
+
+bool parse_hostport(const string &hostport, sockaddr_in6 *addr)
+{
+ memset(addr, 0, sizeof(*addr));
+ addr->sin6_family = AF_INET6;
+
+ string port_string;
+
+ // See if the argument if on the type [ipv6addr]:port.
+ if (!hostport.empty() && hostport[0] == '[') {
+ size_t split = hostport.find("]:");
+ if (split == string::npos) {
+ log(ERROR, "address '%s' is malformed; must be either [ipv6addr]:port or ipv4addr:port");
+ return false;
+ }
+
+ string host(hostport.begin() + 1, hostport.begin() + split);
+ port_string = hostport.substr(split + 2);
+
+ if (inet_pton(AF_INET6, host.c_str(), &addr->sin6_addr) != 1) {
+ log(ERROR, "'%s' is not a valid IPv6 address");
+ return false;
+ }
+ } else {
+ // OK, then it must be ipv4addr:port.
+ size_t split = hostport.find(":");
+ if (split == string::npos) {
+ log(ERROR, "address '%s' is malformed; must be either [ipv6addr]:port or ipv4addr:port");
+ return false;
+ }
+
+ string host(hostport.begin(), hostport.begin() + split);
+ port_string = hostport.substr(split + 1);
+
+ // Parse to an IPv4 address, then construct a mapped-v4 address from that.
+ in_addr addr4;
+
+ if (inet_pton(AF_INET, host.c_str(), &addr4) != 1) {
+ log(ERROR, "'%s' is not a valid IPv4 address");
+ return false;
+ }
+
+ addr->sin6_addr.s6_addr32[2] = htonl(0xffff);
+ addr->sin6_addr.s6_addr32[3] = addr4.s_addr;
+ }
+
+ int port = atoi(port_string.c_str());
+ if (port < 1 || port >= 65536) {
+ log(ERROR, "port %d is out of range (must be [1,65536>).", port);
+ return false;
+ }
+ addr->sin6_port = ntohs(port);
+
+ return true;
+}
+