Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/net/InetSocketAddress.java
38829 views
/*1* Copyright (c) 2000, 2013, 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() {103if (isUnresolved()) {104return hostname + ":" + port;105} else {106return addr.toString() + ":" + port;107}108}109110@Override111public final boolean equals(Object obj) {112if (obj == null || !(obj instanceof InetSocketAddressHolder))113return false;114InetSocketAddressHolder that = (InetSocketAddressHolder)obj;115boolean sameIP;116if (addr != null)117sameIP = addr.equals(that.addr);118else if (hostname != null)119sameIP = (that.addr == null) &&120hostname.equalsIgnoreCase(that.hostname);121else122sameIP = (that.addr == null) && (that.hostname == null);123return sameIP && (port == that.port);124}125126@Override127public final int hashCode() {128if (addr != null)129return addr.hashCode() + port;130if (hostname != null)131return hostname.toLowerCase().hashCode() + port;132return port;133}134}135136private final transient InetSocketAddressHolder holder;137138private static final long serialVersionUID = 5076001401234631237L;139140private static int checkPort(int port) {141if (port < 0 || port > 0xFFFF)142throw new IllegalArgumentException("port out of range:" + port);143return port;144}145146private static String checkHost(String hostname) {147if (hostname == null)148throw new IllegalArgumentException("hostname can't be null");149return hostname;150}151152/**153* Creates a socket address where the IP address is the wildcard address154* and the port number a specified value.155* <p>156* A valid port value is between 0 and 65535.157* A port number of {@code zero} will let the system pick up an158* ephemeral port in a {@code bind} operation.159* <p>160* @param port The port number161* @throws IllegalArgumentException if the port parameter is outside the specified162* range of valid port values.163*/164public InetSocketAddress(int port) {165this(InetAddress.anyLocalAddress(), port);166}167168/**169*170* Creates a socket address from an IP address and a port number.171* <p>172* A valid port value is between 0 and 65535.173* A port number of {@code zero} will let the system pick up an174* ephemeral port in a {@code bind} operation.175* <P>176* A {@code null} address will assign the <i>wildcard</i> address.177* <p>178* @param addr The IP address179* @param port The port number180* @throws IllegalArgumentException if the port parameter is outside the specified181* range of valid port values.182*/183public InetSocketAddress(InetAddress addr, int port) {184holder = new InetSocketAddressHolder(185null,186addr == null ? InetAddress.anyLocalAddress() : addr,187checkPort(port));188}189190/**191*192* Creates a socket address from a hostname and a port number.193* <p>194* An attempt will be made to resolve the hostname into an InetAddress.195* If that attempt fails, the address will be flagged as <I>unresolved</I>.196* <p>197* If there is a security manager, its {@code checkConnect} method198* is called with the host name as its argument to check the permission199* to resolve it. This could result in a SecurityException.200* <P>201* A valid port value is between 0 and 65535.202* A port number of {@code zero} will let the system pick up an203* ephemeral port in a {@code bind} operation.204* <P>205* @param hostname the Host name206* @param port The port number207* @throws IllegalArgumentException if the port parameter is outside the range208* of valid port values, or if the hostname parameter is <TT>null</TT>.209* @throws SecurityException if a security manager is present and210* permission to resolve the host name is211* denied.212* @see #isUnresolved()213*/214public InetSocketAddress(String hostname, int port) {215checkHost(hostname);216InetAddress addr = null;217String host = null;218try {219addr = InetAddress.getByName(hostname);220} catch(UnknownHostException e) {221host = hostname;222}223holder = new InetSocketAddressHolder(host, addr, checkPort(port));224}225226// private constructor for creating unresolved instances227private InetSocketAddress(int port, String hostname) {228holder = new InetSocketAddressHolder(hostname, null, port);229}230231/**232*233* Creates an unresolved socket address from a hostname and a port number.234* <p>235* No attempt will be made to resolve the hostname into an InetAddress.236* The address will be flagged as <I>unresolved</I>.237* <p>238* A valid port value is between 0 and 65535.239* A port number of {@code zero} will let the system pick up an240* ephemeral port in a {@code bind} operation.241* <P>242* @param host the Host name243* @param port The port number244* @throws IllegalArgumentException if the port parameter is outside245* the range of valid port values, or if the hostname246* parameter is <TT>null</TT>.247* @see #isUnresolved()248* @return a {@code InetSocketAddress} representing the unresolved249* socket address250* @since 1.5251*/252public static InetSocketAddress createUnresolved(String host, int port) {253return new InetSocketAddress(checkPort(port), checkHost(host));254}255256/**257* @serialField hostname String258* @serialField addr InetAddress259* @serialField port int260*/261private static final ObjectStreamField[] serialPersistentFields = {262new ObjectStreamField("hostname", String.class),263new ObjectStreamField("addr", InetAddress.class),264new ObjectStreamField("port", int.class)};265266private void writeObject(ObjectOutputStream out)267throws IOException268{269// Don't call defaultWriteObject()270ObjectOutputStream.PutField pfields = out.putFields();271pfields.put("hostname", holder.hostname);272pfields.put("addr", holder.addr);273pfields.put("port", holder.port);274out.writeFields();275}276277private void readObject(ObjectInputStream in)278throws IOException, ClassNotFoundException279{280// Don't call defaultReadObject()281ObjectInputStream.GetField oisFields = in.readFields();282final String oisHostname = (String)oisFields.get("hostname", null);283final InetAddress oisAddr = (InetAddress)oisFields.get("addr", null);284final int oisPort = oisFields.get("port", -1);285286// Check that our invariants are satisfied287checkPort(oisPort);288if (oisHostname == null && oisAddr == null)289throw new InvalidObjectException("hostname and addr " +290"can't both be null");291292InetSocketAddressHolder h = new InetSocketAddressHolder(oisHostname,293oisAddr,294oisPort);295UNSAFE.putObject(this, FIELDS_OFFSET, h);296}297298private void readObjectNoData()299throws ObjectStreamException300{301throw new InvalidObjectException("Stream data required");302}303304private static final long FIELDS_OFFSET;305private static final sun.misc.Unsafe UNSAFE;306static {307try {308sun.misc.Unsafe unsafe = sun.misc.Unsafe.getUnsafe();309FIELDS_OFFSET = unsafe.objectFieldOffset(310InetSocketAddress.class.getDeclaredField("holder"));311UNSAFE = unsafe;312} catch (ReflectiveOperationException e) {313throw new Error(e);314}315}316317/**318* Gets the port number.319*320* @return the port number.321*/322public final int getPort() {323return holder.getPort();324}325326/**327*328* Gets the {@code InetAddress}.329*330* @return the InetAdress or {@code null} if it is unresolved.331*/332public final InetAddress getAddress() {333return holder.getAddress();334}335336/**337* Gets the {@code hostname}.338* Note: This method may trigger a name service reverse lookup if the339* address was created with a literal IP address.340*341* @return the hostname part of the address.342*/343public final String getHostName() {344return holder.getHostName();345}346347/**348* Returns the hostname, or the String form of the address if it349* doesn't have a hostname (it was created using a literal).350* This has the benefit of <b>not</b> attempting a reverse lookup.351*352* @return the hostname, or String representation of the address.353* @since 1.7354*/355public final String getHostString() {356return holder.getHostString();357}358359/**360* Checks whether the address has been resolved or not.361*362* @return {@code true} if the hostname couldn't be resolved into363* an {@code InetAddress}.364*/365public final boolean isUnresolved() {366return holder.isUnresolved();367}368369/**370* Constructs a string representation of this InetSocketAddress.371* This String is constructed by calling toString() on the InetAddress372* and concatenating the port number (with a colon). If the address373* is unresolved then the part before the colon will only contain the hostname.374*375* @return a string representation of this object.376*/377@Override378public String toString() {379return holder.toString();380}381382/**383* Compares this object against the specified object.384* The result is {@code true} if and only if the argument is385* not {@code null} and it represents the same address as386* this object.387* <p>388* Two instances of {@code InetSocketAddress} represent the same389* address if both the InetAddresses (or hostnames if it is unresolved) and port390* numbers are equal.391* If both addresses are unresolved, then the hostname and the port number392* are compared.393*394* Note: Hostnames are case insensitive. e.g. "FooBar" and "foobar" are395* considered equal.396*397* @param obj the object to compare against.398* @return {@code true} if the objects are the same;399* {@code false} otherwise.400* @see java.net.InetAddress#equals(java.lang.Object)401*/402@Override403public final boolean equals(Object obj) {404if (obj == null || !(obj instanceof InetSocketAddress))405return false;406return holder.equals(((InetSocketAddress) obj).holder);407}408409/**410* Returns a hashcode for this socket address.411*412* @return a hash code value for this socket address.413*/414@Override415public final int hashCode() {416return holder.hashCode();417}418}419420421