Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2011 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.net;
 
 import static com.google.common.base.Preconditions.checkArgument;
 import static com.google.common.base.Preconditions.checkNotNull;
 import static com.google.common.base.Preconditions.checkState;
 
 
 
An immutable representation of a host and port.

Example usage:

 HostAndPort hp = HostAndPort.fromString("[2001:db8::1]")
     .withDefaultPort(80)
     .requireBracketsForIPv6();
 hp.getHostText();  // returns "2001:db8::1"
 hp.getPort();      // returns 80
 hp.toString();     // returns "[2001:db8::1]:80"
 

Here are some examples of recognized formats:

Note that this is not an exhaustive list, because these methods are only concerned with brackets, colons, and port numbers. Full validation of the host field (if desired) is the caller's responsibility.

Author(s):
Paul Marks
Since:
10.0
 
 public final class HostAndPort implements Serializable {
  
Magic value indicating the absence of a port number.
 
   private static final int NO_PORT = -1;

  
Hostname, IPv4/IPv6 literal, or unvalidated nonsense.
 
   private final String host;

  
Validated port number in the range [0..65535], or NO_PORT
 
   private final int port;

  
True if the parsed host has colons, but no surrounding brackets.
 
   private final boolean hasBracketlessColons;
 
   private HostAndPort(String hostint portboolean hasBracketlessColons) {
     this. = host;
     this. = port;
     this. = hasBracketlessColons;
   }

  
Returns the portion of this HostAndPort instance that should represent the hostname or IPv4/IPv6 literal. A successful parse does not imply any degree of sanity in this field. For additional validation, see the HostSpecifier class.
 
   public String getHostText() {
     return ;
   }

  
Return true if this instance has a defined port.
 
   public boolean hasPort() {
     return  >= 0;
   }

  
Get the current port number, failing if no port is defined.

Returns:
a validated port number, in the range [0..65535]
Throws:
java.lang.IllegalStateException if no port is defined. You can use withDefaultPort(int) to prevent this from occurring.
  public int getPort() {
    return ;
  }

  
Returns the current port number, with a default if no port is defined.
  public int getPortOrDefault(int defaultPort) {
    return hasPort() ?  : defaultPort;
  }

  
Build a HostAndPort instance from separate host and port values.

Note: Non-bracketed IPv6 literals are allowed. Use requireBracketsForIPv6() to prohibit these.

Parameters:
host the host string to parse. Must not contain a port number.
port a port number from [0..65535]
Returns:
if parsing was successful, a populated HostAndPort object.
Throws:
java.lang.IllegalArgumentException if host contains a port number, or port is out of range.
  public static HostAndPort fromParts(String hostint port) {
    HostAndPort parsedHost = fromString(host);
    checkArgument(!parsedHost.hasPort());
    return new HostAndPort(parsedHost.hostportparsedHost.hasBracketlessColons);
  }
  private static final Pattern BRACKET_PATTERN = Pattern.compile("^\\[(.*:.*)\\](?::(\\d*))?$");

  
Split a freeform string into a host and port, without strict validation. Note that the host-only formats will leave the port field undefined. You can use withDefaultPort(int) to patch in a default value.

Parameters:
hostPortString the input string to parse.
Returns:
if parsing was successful, a populated HostAndPort object.
Throws:
java.lang.IllegalArgumentException if nothing meaningful could be parsed.
  public static HostAndPort fromString(String hostPortString) {
    checkNotNull(hostPortString);
    String host;
    String portString = null;
    boolean hasBracketlessColons = false;
    if (hostPortString.startsWith("[")) {
      // Parse a bracketed host, typically an IPv6 literal.
      Matcher matcher = .matcher(hostPortString);
      checkArgument(matcher.matches(), "Invalid bracketed host/port: %s"hostPortString);
      host = matcher.group(1);
      portString = matcher.group(2);  // could be null
    } else {
      int colonPos = hostPortString.indexOf(':');
      if (colonPos >= 0 && hostPortString.indexOf(':'colonPos + 1) == -1) {
        // Exactly 1 colon.  Split into host:port.
        host = hostPortString.substring(0, colonPos);
        portString = hostPortString.substring(colonPos + 1);
      } else {
        // 0 or 2+ colons.  Bare hostname or IPv6 literal.
        host = hostPortString;
        hasBracketlessColons = (colonPos >= 0);
      }
    }
    int port = ;
    if (portString != null) {
      // Try to parse the whole port string as a number.
      // JDK7 accepts leading plus signs. We don't want to.
      checkArgument(!portString.startsWith("+"), "Unparseable port number: %s"hostPortString);
      try {
        port = Integer.parseInt(portString);
      } catch (NumberFormatException e) {
        throw new IllegalArgumentException("Unparseable port number: " + hostPortString);
      }
      checkArgument(isValidPort(port), "Port number out of range: %s"hostPortString);
    }
    return new HostAndPort(hostporthasBracketlessColons);
  }

  
Provide a default port if the parsed string contained only a host. You can chain this after fromString(java.lang.String) to include a port in case the port was omitted from the input string. If a port was already provided, then this method is a no-op.

Parameters:
defaultPort a port number, from [0..65535]
Returns:
a HostAndPort instance, guaranteed to have a defined port.
  public HostAndPort withDefaultPort(int defaultPort) {
    checkArgument(isValidPort(defaultPort));
    if (hasPort() ||  == defaultPort) {
      return this;
    }
    return new HostAndPort(defaultPort);
  }

  
Generate an error if the host might be a non-bracketed IPv6 literal.

URI formatting requires that IPv6 literals be surrounded by brackets, like "[2001:db8::1]". Chain this call after fromString(java.lang.String) to increase the strictness of the parser, and disallow IPv6 literals that don't contain these brackets.

Note that this parser identifies IPv6 literals solely based on the presence of a colon. To perform actual validation of IP addresses, see the InetAddresses.forString(java.lang.String) method.

Returns:
this, to enable chaining of calls.
Throws:
java.lang.IllegalArgumentException if bracketless IPv6 is detected.
    checkArgument(!"Possible bracketless IPv6 literal: %s");
    return this;
  }
  public boolean equals(Object other) {
    if (this == other) {
      return true;
    }
    if (other instanceof HostAndPort) {
      HostAndPort that = (HostAndPortother;
      return Objects.equal(this.that.host)
          && this. == that.port
          && this. == that.hasBracketlessColons;
    }
    return false;
  }
  public int hashCode() {
    return Objects.hashCode();
  }

  
Rebuild the host:port string, including brackets if necessary.
  public String toString() {
    StringBuilder builder = new StringBuilder(.length() + 7);
    if (.indexOf(':') >= 0) {
      builder.append('[').append().append(']');
    } else {
      builder.append();
    }
    if (hasPort()) {
      builder.append(':').append();
    }
    return builder.toString();
  }

  
Return true for valid port numbers.
  private static boolean isValidPort(int port) {
    return port >= 0 && port <= 65535;
  }
  private static final long serialVersionUID = 0;
New to GrepCode? Check out our FAQ X