Top Description Fields Constructors Methods
com.google.common.net

public final Class HostAndPort

extends Object
implements Serializable
Class Inheritance
All Implemented Interfaces
java.io.Serializable
Annotations
@Immutable
@GwtCompatible
@ElementTypesAreNonnullByDefault
Static Imports
com.google.common.base.Preconditions.checkArgument, .Preconditions.checkNotNull, .Preconditions.checkState

An immutable representation of a host and port.

Example usage:

HostAndPort hp = HostAndPort.fromString("[2001:db8::1]")
    .withDefaultPort(80)
    .requireBracketsForIPv6();
hp.getHost();   // 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
Paul Marks
Since
10.0

Field Summary

Modifier and TypeField and Description
private final boolean
hasBracketlessColons

True if the parsed host has colons, but no surrounding brackets.

private final String
host

Hostname, IPv4/IPv6 literal, or unvalidated nonsense.

private static final int
NO_PORT

Magic value indicating the absence of a port number.

private final int
port

Validated port number in the range [0..65535], or NO_PORT

private static final long

Constructor Summary

AccessConstructor and Description
private
HostAndPort(String host, int port, boolean hasBracketlessColons)

Method Summary

Modifier and TypeMethod and Description
public boolean
equals(Object
the reference object with which to compare.
other
)

Overrides java.lang.Object.equals.

Indicates whether some other object is "equal to" this one.
public static HostAndPort

Returns:

if parsing was successful, a populated HostAndPort object.
fromHost
(String
the host-only string to parse. Must not contain a port number.
host
)

Build a HostAndPort instance from a host only.

public static HostAndPort

Returns:

if parsing was successful, a populated HostAndPort object.
fromParts
(String
the host string to parse. Must not contain a port number.
host
,
int
a port number from [0..65535]
port
)

Build a HostAndPort instance from separate host and port values.

public static HostAndPort

Returns:

if parsing was successful, a populated HostAndPort object.
fromString
(String
the input string to parse.
hostPortString
)

Split a freeform string into a host and port, without strict validation.

public String
getHost()

Returns the portion of this HostAndPort instance that should represent the hostname or IPv4/IPv6 literal.

private static String[]

Returns:

an array with 2 strings: host and port, in that order.
getHostAndPortFromBracketedHost
(String
the full bracketed host-port specification. Post might not be specified.
hostPortString
)

Parses a bracketed host-port string, throwing IllegalArgumentException if parsing fails.

public int

Returns:

a validated port number, in the range [0..65535]
getPort
()

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

public int
getPortOrDefault(int defaultPort)

Returns the current port number, with a default if no port is defined.

public int
hashCode()

Overrides java.lang.Object.hashCode.

Returns a hash code value for the object.
public boolean
hasPort()

Return true if this instance has a defined port.

private static boolean
isValidPort(int port)

Return true for valid port numbers.

public HostAndPort

Returns:

this, to enable chaining of calls.
requireBracketsForIPv6
()

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

public String
toString()

Overrides java.lang.Object.toString.

Rebuild the host:port string, including brackets if necessary.
public HostAndPort

Returns:

a HostAndPort instance, guaranteed to have a defined port.
withDefaultPort
(int
a port number, from [0..65535]
defaultPort
)

Provide a default port if the parsed string contained only a host.

Inherited from java.lang.Object:
clonefinalizegetClassnotifynotifyAllwaitwaitwait

Field Detail

hasBracketlessColonsback to summary
private final boolean hasBracketlessColons

True if the parsed host has colons, but no surrounding brackets.

hostback to summary
private final String host

Hostname, IPv4/IPv6 literal, or unvalidated nonsense.

NO_PORTback to summary
private static final int NO_PORT

Magic value indicating the absence of a port number.

portback to summary
private final int port

Validated port number in the range [0..65535], or NO_PORT

serialVersionUIDback to summary
private static final long serialVersionUID

Constructor Detail

HostAndPortback to summary
private HostAndPort(String host, int port, boolean hasBracketlessColons)

Method Detail

equalsback to summary
public boolean equals(Object other)

Overrides java.lang.Object.equals.

Doc from java.lang.Object.equals.

Indicates whether some other object is "equal to" this one.

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.

An equivalence relation partitions the elements it operates on into equivalence classes; all the members of an equivalence class are equal to each other. Members of an equivalence class are substitutable for each other, at least for some purposes.

Parameters
other:Object

the reference object with which to compare.

Returns:boolean

true if this object is the same as the obj argument; false otherwise.

Annotations
@Override
fromHostback to summary
public static HostAndPort fromHost(String host)

Build a HostAndPort instance from a host only.

Note

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

Parameters
host:String

the host-only string to parse. Must not contain a port number.

Returns:HostAndPort

if parsing was successful, a populated HostAndPort object.

Exceptions
IllegalArgumentException:
if host contains a port number.
Since
17.0
fromPartsback to summary
public static HostAndPort fromParts(String host, int port)

Build a HostAndPort instance from separate host and port values.

Note

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

Parameters
host:String

the host string to parse. Must not contain a port number.

port:int

a port number from [0..65535]

Returns:HostAndPort

if parsing was successful, a populated HostAndPort object.

Exceptions
IllegalArgumentException:
if host contains a port number, or port is out of range.
fromStringback to summary
public static HostAndPort fromString(String hostPortString)

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:String

the input string to parse.

Returns:HostAndPort

if parsing was successful, a populated HostAndPort object.

Annotations
@CanIgnoreReturnValue
Exceptions
IllegalArgumentException:
if nothing meaningful could be parsed.
getHostback to summary
public String getHost()

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.

Since
20.0 (since 10.0 as getHostText)
getHostAndPortFromBracketedHostback to summary
private static String[] getHostAndPortFromBracketedHost(String hostPortString)

Parses a bracketed host-port string, throwing IllegalArgumentException if parsing fails.

Parameters
hostPortString:String

the full bracketed host-port specification. Post might not be specified.

Returns:String[]

an array with 2 strings: host and port, in that order.

Exceptions
IllegalArgumentException:
if parsing the bracketed host-port string fails.
getPortback to summary
public int getPort()

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

Returns:int

a validated port number, in the range [0..65535]

Exceptions
IllegalStateException:
if no port is defined. You can use withDefaultPort(int) to prevent this from occurring.
getPortOrDefaultback to summary
public int getPortOrDefault(int defaultPort)

Returns the current port number, with a default if no port is defined.

hashCodeback to summary
public int hashCode()

Overrides java.lang.Object.hashCode.

Doc from java.lang.Object.hashCode.

Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by java.util.HashMap.

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
Returns:int

a hash code value for this object.

Annotations
@Override
hasPortback to summary
public boolean hasPort()

Return true if this instance has a defined port.

isValidPortback to summary
private static boolean isValidPort(int port)

Return true for valid port numbers.

requireBracketsForIPv6back to summary
public HostAndPort requireBracketsForIPv6()

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(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(String) method.

Returns:HostAndPort

this, to enable chaining of calls.

Annotations
@CanIgnoreReturnValue
Exceptions
IllegalArgumentException:
if bracketless IPv6 is detected.
toStringback to summary
public String toString()

Overrides java.lang.Object.toString.

Rebuild the host:port string, including brackets if necessary.

Returns:String

Doc from java.lang.Object.toString.

a string representation of the object.

Annotations
@Override
withDefaultPortback to summary
public HostAndPort withDefaultPort(int defaultPort)

Provide a default port if the parsed string contained only a host.

You can chain this after fromString(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:int

a port number, from [0..65535]

Returns:HostAndPort

a HostAndPort instance, guaranteed to have a defined port.