001/* 002 * Copyright (C) 2011 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.net; 016 017import static com.google.common.base.Preconditions.checkArgument; 018import static com.google.common.base.Preconditions.checkNotNull; 019import static com.google.common.base.Preconditions.checkState; 020 021import com.google.common.annotations.GwtCompatible; 022import com.google.common.base.CharMatcher; 023import com.google.common.base.Objects; 024import com.google.common.base.Strings; 025import com.google.errorprone.annotations.CanIgnoreReturnValue; 026import com.google.errorprone.annotations.Immutable; 027import java.io.Serializable; 028import javax.annotation.CheckForNull; 029 030/** 031 * An immutable representation of a host and port. 032 * 033 * <p>Example usage: 034 * 035 * <pre> 036 * HostAndPort hp = HostAndPort.fromString("[2001:db8::1]") 037 * .withDefaultPort(80) 038 * .requireBracketsForIPv6(); 039 * hp.getHost(); // returns "2001:db8::1" 040 * hp.getPort(); // returns 80 041 * hp.toString(); // returns "[2001:db8::1]:80" 042 * </pre> 043 * 044 * <p>Here are some examples of recognized formats: 045 * 046 * <ul> 047 * <li>example.com 048 * <li>example.com:80 049 * <li>192.0.2.1 050 * <li>192.0.2.1:80 051 * <li>[2001:db8::1] - {@link #getHost()} omits brackets 052 * <li>[2001:db8::1]:80 - {@link #getHost()} omits brackets 053 * <li>2001:db8::1 - Use {@link #requireBracketsForIPv6()} to prohibit this 054 * </ul> 055 * 056 * <p>Note that this is not an exhaustive list, because these methods are only concerned with 057 * brackets, colons, and port numbers. Full validation of the host field (if desired) is the 058 * caller's responsibility. 059 * 060 * @author Paul Marks 061 * @since 10.0 062 */ 063@Immutable 064@GwtCompatible 065@ElementTypesAreNonnullByDefault 066public final class HostAndPort implements Serializable { 067 /** Magic value indicating the absence of a port number. */ 068 private static final int NO_PORT = -1; 069 070 /** Hostname, IPv4/IPv6 literal, or unvalidated nonsense. */ 071 private final String host; 072 073 /** Validated port number in the range [0..65535], or NO_PORT */ 074 private final int port; 075 076 /** True if the parsed host has colons, but no surrounding brackets. */ 077 private final boolean hasBracketlessColons; 078 079 private HostAndPort(String host, int port, boolean hasBracketlessColons) { 080 this.host = host; 081 this.port = port; 082 this.hasBracketlessColons = hasBracketlessColons; 083 } 084 085 /** 086 * Returns the portion of this {@code HostAndPort} instance that should represent the hostname or 087 * IPv4/IPv6 literal. 088 * 089 * <p>A successful parse does not imply any degree of sanity in this field. For additional 090 * validation, see the {@link HostSpecifier} class. 091 * 092 * @since 20.0 (since 10.0 as {@code getHostText}) 093 */ 094 public String getHost() { 095 return host; 096 } 097 098 /** Return true if this instance has a defined port. */ 099 public boolean hasPort() { 100 return port >= 0; 101 } 102 103 /** 104 * Get the current port number, failing if no port is defined. 105 * 106 * @return a validated port number, in the range [0..65535] 107 * @throws IllegalStateException if no port is defined. You can use {@link #withDefaultPort(int)} 108 * to prevent this from occurring. 109 */ 110 public int getPort() { 111 checkState(hasPort()); 112 return port; 113 } 114 115 /** Returns the current port number, with a default if no port is defined. */ 116 public int getPortOrDefault(int defaultPort) { 117 return hasPort() ? port : defaultPort; 118 } 119 120 /** 121 * Build a HostAndPort instance from separate host and port values. 122 * 123 * <p>Note: Non-bracketed IPv6 literals are allowed. Use {@link #requireBracketsForIPv6()} to 124 * prohibit these. 125 * 126 * @param host the host string to parse. Must not contain a port number. 127 * @param port a port number from [0..65535] 128 * @return if parsing was successful, a populated HostAndPort object. 129 * @throws IllegalArgumentException if {@code host} contains a port number, or {@code port} is out 130 * of range. 131 */ 132 public static HostAndPort fromParts(String host, int port) { 133 checkArgument(isValidPort(port), "Port out of range: %s", port); 134 HostAndPort parsedHost = fromString(host); 135 checkArgument(!parsedHost.hasPort(), "Host has a port: %s", host); 136 return new HostAndPort(parsedHost.host, port, parsedHost.hasBracketlessColons); 137 } 138 139 /** 140 * Build a HostAndPort instance from a host only. 141 * 142 * <p>Note: Non-bracketed IPv6 literals are allowed. Use {@link #requireBracketsForIPv6()} to 143 * prohibit these. 144 * 145 * @param host the host-only string to parse. Must not contain a port number. 146 * @return if parsing was successful, a populated HostAndPort object. 147 * @throws IllegalArgumentException if {@code host} contains a port number. 148 * @since 17.0 149 */ 150 public static HostAndPort fromHost(String host) { 151 HostAndPort parsedHost = fromString(host); 152 checkArgument(!parsedHost.hasPort(), "Host has a port: %s", host); 153 return parsedHost; 154 } 155 156 /** 157 * Split a freeform string into a host and port, without strict validation. 158 * 159 * <p>Note that the host-only formats will leave the port field undefined. You can use {@link 160 * #withDefaultPort(int)} to patch in a default value. 161 * 162 * @param hostPortString the input string to parse. 163 * @return if parsing was successful, a populated HostAndPort object. 164 * @throws IllegalArgumentException if nothing meaningful could be parsed. 165 */ 166 @CanIgnoreReturnValue // TODO(b/219820829): consider removing 167 public static HostAndPort fromString(String hostPortString) { 168 checkNotNull(hostPortString); 169 String host; 170 String portString = null; 171 boolean hasBracketlessColons = false; 172 173 if (hostPortString.startsWith("[")) { 174 String[] hostAndPort = getHostAndPortFromBracketedHost(hostPortString); 175 host = hostAndPort[0]; 176 portString = hostAndPort[1]; 177 } else { 178 int colonPos = hostPortString.indexOf(':'); 179 if (colonPos >= 0 && hostPortString.indexOf(':', colonPos + 1) == -1) { 180 // Exactly 1 colon. Split into host:port. 181 host = hostPortString.substring(0, colonPos); 182 portString = hostPortString.substring(colonPos + 1); 183 } else { 184 // 0 or 2+ colons. Bare hostname or IPv6 literal. 185 host = hostPortString; 186 hasBracketlessColons = (colonPos >= 0); 187 } 188 } 189 190 int port = NO_PORT; 191 if (!Strings.isNullOrEmpty(portString)) { 192 // Try to parse the whole port string as a number. 193 // Java accepts leading plus signs. We don't want to. 194 checkArgument( 195 !portString.startsWith("+") && CharMatcher.ascii().matchesAllOf(portString), 196 "Unparseable port number: %s", 197 hostPortString); 198 try { 199 port = Integer.parseInt(portString); 200 } catch (NumberFormatException e) { 201 throw new IllegalArgumentException("Unparseable port number: " + hostPortString); 202 } 203 checkArgument(isValidPort(port), "Port number out of range: %s", hostPortString); 204 } 205 206 return new HostAndPort(host, port, hasBracketlessColons); 207 } 208 209 /** 210 * Parses a bracketed host-port string, throwing IllegalArgumentException if parsing fails. 211 * 212 * @param hostPortString the full bracketed host-port specification. Port might not be specified. 213 * @return an array with 2 strings: host and port, in that order. 214 * @throws IllegalArgumentException if parsing the bracketed host-port string fails. 215 */ 216 private static String[] getHostAndPortFromBracketedHost(String hostPortString) { 217 checkArgument( 218 hostPortString.charAt(0) == '[', 219 "Bracketed host-port string must start with a bracket: %s", 220 hostPortString); 221 int colonIndex = hostPortString.indexOf(':'); 222 int closeBracketIndex = hostPortString.lastIndexOf(']'); 223 checkArgument( 224 colonIndex > -1 && closeBracketIndex > colonIndex, 225 "Invalid bracketed host/port: %s", 226 hostPortString); 227 228 String host = hostPortString.substring(1, closeBracketIndex); 229 if (closeBracketIndex + 1 == hostPortString.length()) { 230 return new String[] {host, ""}; 231 } else { 232 checkArgument( 233 hostPortString.charAt(closeBracketIndex + 1) == ':', 234 "Only a colon may follow a close bracket: %s", 235 hostPortString); 236 for (int i = closeBracketIndex + 2; i < hostPortString.length(); ++i) { 237 checkArgument( 238 Character.isDigit(hostPortString.charAt(i)), 239 "Port must be numeric: %s", 240 hostPortString); 241 } 242 return new String[] {host, hostPortString.substring(closeBracketIndex + 2)}; 243 } 244 } 245 246 /** 247 * Provide a default port if the parsed string contained only a host. 248 * 249 * <p>You can chain this after {@link #fromString(String)} to include a port in case the port was 250 * omitted from the input string. If a port was already provided, then this method is a no-op. 251 * 252 * @param defaultPort a port number, from [0..65535] 253 * @return a HostAndPort instance, guaranteed to have a defined port. 254 */ 255 public HostAndPort withDefaultPort(int defaultPort) { 256 checkArgument(isValidPort(defaultPort)); 257 if (hasPort()) { 258 return this; 259 } 260 return new HostAndPort(host, defaultPort, hasBracketlessColons); 261 } 262 263 /** 264 * Generate an error if the host might be a non-bracketed IPv6 literal. 265 * 266 * <p>URI formatting requires that IPv6 literals be surrounded by brackets, like "[2001:db8::1]". 267 * Chain this call after {@link #fromString(String)} to increase the strictness of the parser, and 268 * disallow IPv6 literals that don't contain these brackets. 269 * 270 * <p>Note that this parser identifies IPv6 literals solely based on the presence of a colon. To 271 * perform actual validation of IP addresses, see the {@link InetAddresses#forString(String)} 272 * method. 273 * 274 * @return {@code this}, to enable chaining of calls. 275 * @throws IllegalArgumentException if bracketless IPv6 is detected. 276 */ 277 @CanIgnoreReturnValue 278 public HostAndPort requireBracketsForIPv6() { 279 checkArgument(!hasBracketlessColons, "Possible bracketless IPv6 literal: %s", host); 280 return this; 281 } 282 283 @Override 284 public boolean equals(@CheckForNull Object other) { 285 if (this == other) { 286 return true; 287 } 288 if (other instanceof HostAndPort) { 289 HostAndPort that = (HostAndPort) other; 290 return Objects.equal(this.host, that.host) && this.port == that.port; 291 } 292 return false; 293 } 294 295 @Override 296 public int hashCode() { 297 return Objects.hashCode(host, port); 298 } 299 300 /** Rebuild the host:port string, including brackets if necessary. */ 301 @Override 302 public String toString() { 303 // "[]:12345" requires 8 extra bytes. 304 StringBuilder builder = new StringBuilder(host.length() + 8); 305 if (host.indexOf(':') >= 0) { 306 builder.append('[').append(host).append(']'); 307 } else { 308 builder.append(host); 309 } 310 if (hasPort()) { 311 builder.append(':').append(port); 312 } 313 return builder.toString(); 314 } 315 316 /** Return true for valid port numbers. */ 317 private static boolean isValidPort(int port) { 318 return port >= 0 && port <= 65535; 319 } 320 321 private static final long serialVersionUID = 0; 322}