Split a freeform string into a host and port, without strict validation. <p>Note that the host-only formats will leave the port field undefined. You can use {@link #withDefaultPort(int)} to patch in a default value. @param hostPortString the input string to parse. @return if parsing was successful
(String hostPortString)
| 166 | * @throws IllegalArgumentException if nothing meaningful could be parsed. |
| 167 | */ |
| 168 | @CanIgnoreReturnValue // TODO(b/219820829): consider removing |
| 169 | public static HostAndPort fromString(String hostPortString) { |
| 170 | checkNotNull(hostPortString); |
| 171 | String host; |
| 172 | String portString = null; |
| 173 | boolean hasBracketlessColons = false; |
| 174 | |
| 175 | if (hostPortString.startsWith("[")) { |
| 176 | String[] hostAndPort = getHostAndPortFromBracketedHost(hostPortString); |
| 177 | host = hostAndPort[0]; |
| 178 | portString = hostAndPort[1]; |
| 179 | } else { |
| 180 | int colonPos = hostPortString.indexOf(':'); |
| 181 | if (colonPos >= 0 && hostPortString.indexOf(':', colonPos + 1) == -1) { |
| 182 | // Exactly 1 colon. Split into host:port. |
| 183 | host = hostPortString.substring(0, colonPos); |
| 184 | portString = hostPortString.substring(colonPos + 1); |
| 185 | } else { |
| 186 | // 0 or 2+ colons. Bare hostname or IPv6 literal. |
| 187 | host = hostPortString; |
| 188 | hasBracketlessColons = colonPos >= 0; |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | Integer port; |
| 193 | if (isNullOrEmpty(portString)) { |
| 194 | port = NO_PORT; |
| 195 | } else { |
| 196 | port = Ints.tryParse(portString); |
| 197 | checkArgument(port != null, "Unparseable port number: %s", hostPortString); |
| 198 | checkArgument(isValidPort(port), "Port number out of range: %s", hostPortString); |
| 199 | } |
| 200 | |
| 201 | return new HostAndPort(host, port, hasBracketlessColons); |
| 202 | } |
| 203 | |
| 204 | /** |
| 205 | * Parses a bracketed host-port string, throwing IllegalArgumentException if parsing fails. |