Path: blob/master/src/java.base/share/classes/java/net/InetSocketAddress.java
41152 views
/*1* Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/24package java.net;2526import java.io.IOException;27import java.io.InvalidObjectException;28import java.io.ObjectInputStream;29import java.io.ObjectOutputStream;30import java.io.ObjectStreamException;31import java.io.ObjectStreamField;3233/**34*35* This class implements an IP Socket Address (IP address + port number)36* It can also be a pair (hostname + port number), in which case an attempt37* will be made to resolve the hostname. If resolution fails then the address38* is said to be <I>unresolved</I> but can still be used on some circumstances39* like connecting through a proxy.40* <p>41* It provides an immutable object used by sockets for binding, connecting, or42* as returned values.43* <p>44* The <i>wildcard</i> is a special local IP address. It usually means "any"45* and can only be used for {@code bind} operations.46*47* @see java.net.Socket48* @see java.net.ServerSocket49* @since 1.450*/51public class InetSocketAddress52extends SocketAddress53{54// Private implementation class pointed to by all public methods.55private static class InetSocketAddressHolder {56// The hostname of the Socket Address57private String hostname;58// The IP address of the Socket Address59private InetAddress addr;60// The port number of the Socket Address61private int port;6263private InetSocketAddressHolder(String hostname, InetAddress addr, int port) {64this.hostname = hostname;65this.addr = addr;66this.port = port;67}6869private int getPort() {70return port;71}7273private InetAddress getAddress() {74return addr;75}7677private String getHostName() {78if (hostname != null)79return hostname;80if (addr != null)81return addr.getHostName();82return null;83}8485private String getHostString() {86if (hostname != null)87return hostname;88if (addr != null) {89if (addr.holder().getHostName() != null)90return addr.holder().getHostName();91else92return addr.getHostAddress();93}94return null;95}9697private boolean isUnresolved() {98return addr == null;99}100101@Override102public String toString() {103104String formatted;105106if (isUnresolved()) {107formatted = hostname + "/<unresolved>";108} else {109formatted = addr.toString();110if (addr instanceof Inet6Address) {111int i = formatted.lastIndexOf("/");112formatted = formatted.substring(0, i + 1)113+ "[" + formatted.substring(i + 1) + "]";114}115}116return formatted + ":" + port;117}118119@Override120public final boolean equals(Object obj) {121if (!(obj instanceof InetSocketAddressHolder that))122return false;123boolean sameIP;124if (addr != null)125sameIP = addr.equals(that.addr);126else if (hostname != null)127sameIP = (that.addr == null) &&128hostname.equalsIgnoreCase(that.hostname);129else130sameIP = (that.addr == null) && (that.hostname == null);131return sameIP && (port == that.port);132}133134@Override135public final int hashCode() {136if (addr != null)137return addr.hashCode() + port;138if (hostname != null)139return hostname.toLowerCase().hashCode() + port;140return port;141}142}143144private final transient InetSocketAddressHolder holder;145146@java.io.Serial147private static final long serialVersionUID = 5076001401234631237L;148149private static int checkPort(int port) {150if (port < 0 || port > 0xFFFF)151throw new IllegalArgumentException("port out of range:" + port);152return port;153}154155private static String checkHost(String hostname) {156if (hostname == null)157throw new IllegalArgumentException("hostname can't be null");158return hostname;159}160161/**162* Creates a socket address where the IP address is the wildcard address163* and the port number a specified value.164* <p>165* A valid port value is between 0 and 65535.166* A port number of {@code zero} will let the system pick up an167* ephemeral port in a {@code bind} operation.168*169* @param port The port number170* @throws IllegalArgumentException if the port parameter is outside the specified171* range of valid port values.172*/173public InetSocketAddress(int port) {174this(InetAddress.anyLocalAddress(), port);175}176177/**178*179* Creates a socket address from an IP address and a port number.180* <p>181* A valid port value is between 0 and 65535.182* A port number of {@code zero} will let the system pick up an183* ephemeral port in a {@code bind} operation.184* <P>185* A {@code null} address will assign the <i>wildcard</i> address.186*187* @param addr The IP address188* @param port The port number189* @throws IllegalArgumentException if the port parameter is outside the specified190* range of valid port values.191*/192public InetSocketAddress(InetAddress addr, int port) {193holder = new InetSocketAddressHolder(194null,195addr == null ? InetAddress.anyLocalAddress() : addr,196checkPort(port));197}198199/**200*201* Creates a socket address from a hostname and a port number.202* <p>203* An attempt will be made to resolve the hostname into an InetAddress.204* If that attempt fails, the address will be flagged as <I>unresolved</I>.205* <p>206* If there is a security manager, its {@code checkConnect} method207* is called with the host name as its argument to check the permission208* to resolve it. This could result in a SecurityException.209* <P>210* A valid port value is between 0 and 65535.211* A port number of {@code zero} will let the system pick up an212* ephemeral port in a {@code bind} operation.213*214* @param hostname the Host name215* @param port The port number216* @throws IllegalArgumentException if the port parameter is outside the range217* of valid port values, or if the hostname parameter is {@code null}.218* @throws SecurityException if a security manager is present and219* permission to resolve the host name is220* denied.221* @see #isUnresolved()222*/223public InetSocketAddress(String hostname, int port) {224checkHost(hostname);225InetAddress addr = null;226String host = null;227try {228addr = InetAddress.getByName(hostname);229} catch(UnknownHostException e) {230host = hostname;231}232holder = new InetSocketAddressHolder(host, addr, checkPort(port));233}234235// private constructor for creating unresolved instances236private InetSocketAddress(int port, String hostname) {237holder = new InetSocketAddressHolder(hostname, null, port);238}239240/**241*242* Creates an unresolved socket address from a hostname and a port number.243* <p>244* No attempt will be made to resolve the hostname into an InetAddress.245* The address will be flagged as <I>unresolved</I>.246* <p>247* A valid port value is between 0 and 65535.248* A port number of {@code zero} will let the system pick up an249* ephemeral port in a {@code bind} operation.250*251* @param host the Host name252* @param port The port number253* @throws IllegalArgumentException if the port parameter is outside254* the range of valid port values, or if the hostname255* parameter is {@code null}.256* @see #isUnresolved()257* @return an {@code InetSocketAddress} representing the unresolved258* socket address259* @since 1.5260*/261public static InetSocketAddress createUnresolved(String host, int port) {262return new InetSocketAddress(checkPort(port), checkHost(host));263}264265/**266* @serialField hostname String the hostname of the Socket Address267* @serialField addr InetAddress the IP address of the Socket Address268* @serialField port int the port number of the Socket Address269*/270@java.io.Serial271private static final ObjectStreamField[] serialPersistentFields = {272new ObjectStreamField("hostname", String.class),273new ObjectStreamField("addr", InetAddress.class),274new ObjectStreamField("port", int.class)};275276/**277* Writes the state of this object to the stream.278*279* @param out the {@code ObjectOutputStream} to which data is written280* @throws IOException if an I/O error occurs281*/282@java.io.Serial283private void writeObject(ObjectOutputStream out)284throws IOException285{286// Don't call defaultWriteObject()287ObjectOutputStream.PutField pfields = out.putFields();288pfields.put("hostname", holder.hostname);289pfields.put("addr", holder.addr);290pfields.put("port", holder.port);291out.writeFields();292}293294/**295* Restores the state of this object from the stream.296*297* @param in the {@code ObjectInputStream} from which data is read298* @throws IOException if an I/O error occurs299* @throws ClassNotFoundException if a serialized class cannot be loaded300*/301@java.io.Serial302private void readObject(ObjectInputStream in)303throws IOException, ClassNotFoundException304{305// Don't call defaultReadObject()306ObjectInputStream.GetField oisFields = in.readFields();307final String oisHostname = (String)oisFields.get("hostname", null);308final InetAddress oisAddr = (InetAddress)oisFields.get("addr", null);309final int oisPort = oisFields.get("port", -1);310311// Check that our invariants are satisfied312checkPort(oisPort);313if (oisHostname == null && oisAddr == null)314throw new InvalidObjectException("hostname and addr " +315"can't both be null");316317InetSocketAddressHolder h = new InetSocketAddressHolder(oisHostname,318oisAddr,319oisPort);320UNSAFE.putReference(this, FIELDS_OFFSET, h);321}322323/**324* Throws {@code InvalidObjectException}, always.325* @throws ObjectStreamException always326*/327@java.io.Serial328private void readObjectNoData()329throws ObjectStreamException330{331throw new InvalidObjectException("Stream data required");332}333334private static final jdk.internal.misc.Unsafe UNSAFE335= jdk.internal.misc.Unsafe.getUnsafe();336private static final long FIELDS_OFFSET337= UNSAFE.objectFieldOffset(InetSocketAddress.class, "holder");338339/**340* Gets the port number.341*342* @return the port number.343*/344public final int getPort() {345return holder.getPort();346}347348/**349* Gets the {@code InetAddress}.350*351* @return the InetAddress or {@code null} if it is unresolved.352*/353public final InetAddress getAddress() {354return holder.getAddress();355}356357/**358* Gets the {@code hostname}.359* Note: This method may trigger a name service reverse lookup if the360* address was created with a literal IP address.361*362* @return the hostname part of the address.363*/364public final String getHostName() {365return holder.getHostName();366}367368/**369* Returns the hostname, or the String form of the address if it370* doesn't have a hostname (it was created using a literal).371* This has the benefit of <b>not</b> attempting a reverse lookup.372*373* @return the hostname, or String representation of the address.374* @since 1.7375*/376public final String getHostString() {377return holder.getHostString();378}379380/**381* Checks whether the address has been resolved or not.382*383* @return {@code true} if the hostname couldn't be resolved into384* an {@code InetAddress}.385*/386public final boolean isUnresolved() {387return holder.isUnresolved();388}389390/**391* Constructs a string representation of this InetSocketAddress.392* This string is constructed by calling {@link InetAddress#toString()}393* on the InetAddress and concatenating the port number (with a colon).394* <p>395* If the address is an IPv6 address, the IPv6 literal is enclosed in396* square brackets, for example: {@code "localhost/[0:0:0:0:0:0:0:1]:80"}.397* If the address is {@linkplain #isUnresolved() unresolved},398* {@code <unresolved>} is displayed in place of the address literal, for399* example {@code "foo/<unresolved>:80"}.400* <p>401* To retrieve a string representation of the hostname or the address, use402* {@link #getHostString()}, rather than parsing the string returned by this403* {@link #toString()} method.404*405* @return a string representation of this object.406*/407@Override408public String toString() {409return holder.toString();410}411412/**413* Compares this object against the specified object.414* The result is {@code true} if and only if the argument is415* not {@code null} and it represents the same address as416* this object.417* <p>418* Two instances of {@code InetSocketAddress} represent the same419* address if both the InetAddresses (or hostnames if it is unresolved) and port420* numbers are equal.421* If both addresses are unresolved, then the hostname and the port number422* are compared.423*424* Note: Hostnames are case insensitive. e.g. "FooBar" and "foobar" are425* considered equal.426*427* @param obj the object to compare against.428* @return {@code true} if the objects are the same;429* {@code false} otherwise.430* @see java.net.InetAddress#equals(java.lang.Object)431*/432@Override433public final boolean equals(Object obj) {434if (obj instanceof InetSocketAddress addr) {435return holder.equals(addr.holder);436}437return false;438}439440/**441* Returns a hashcode for this socket address.442*443* @return a hash code value for this socket address.444*/445@Override446public final int hashCode() {447return holder.hashCode();448}449}450451452