9.5 Socket Addresses
The SocketAddress class introduced in Java 1.4 represents a
connection endpoint. The actual
java.net.SocketAddress class is an empty abstract
class with no methods aside from a default constructor:
package java.net.*;At least theoretically, this class can be used for both TCP and
public abstract class SocketAddress {
public SocketAddress( ) {}
}
non-TCP sockets. Subclasses of SocketAddress
provide more detailed information appropriate for the type of socket.
In practice, only TCP/IP sockets are currently supported.The primary purpose of the SocketAddress class is
to provide a convenient store for transient socket connection
information such as the IP address and port that can be reused to
create new sockets, even after the original socket is disconnected
and garbage collected. To this end, the Socket
class offers two methods that return SocketAddress
objects: getRemoteSocketAddress( )
returns the address of the system being connected to and
getLocalSocketAdddress( ) returns the address from
which the connection is made:
public SocketAddress getRemoteSocketAddress( )Both of these methods return null if the socket is not yet connected.A SocketAddress is necessary to connect an
public SocketAddress getLocalSocketAddress( )
unconnected socket via the connect( ) method:
public void connect(SocketAddress endpoint) throws IOExceptionFor example, first you might connect to Yahoo, then store its address:
Socket socket = new Socket("www.yahoo.com", 80);Later, you could reconnect to Yahoo using this address:
SocketAddress yahoo = socket.getRemoteSocketAddress( );
socket.close( );
socket = new Socket( );Not all socket implementations can use the same subclasses of
socket.connect(yahoo);
SocketAddress. If an instance of the wrong type is
passed to connect( ), it throws an
IllegalArgumentException.You can pass an int as the second argument to
specify the number of milliseconds to wait before the connection
times out:
public void connect(SocketAddress endpoint, int timeout) throws IOExceptionThe default, 0, means wait forever.