Java Reference
In-Depth Information
public SocketAddress getRemoteSocketAddress ()
public SocketAddress getLocalSocketAddress ()
Both of these methods return null if the socket is not yet connected. For example, first
you might connect to Yahoo! then store its address:
Socket socket = new Socket ( "www.yahoo.com" , 80 );
SocketAddress yahoo = socket . getRemoteSocketAddress ();
socket . close ();
Later, you could reconnect to Yahoo! using this address:
Socket socket2 = new Socket ();
socket2 . connect ( yahoo );
The InetSocketAddress class (which is the only subclass of SocketAddress in the JDK,
and the only subclass I've ever encountered) is usually created with a host and a port
(for clients) or just a port (for servers):
public InetSocketAddress ( InetAddress address , int port )
public InetSocketAddress ( String host , int port )
public InetSocketAddress ( int port )
You can also use the static factory method InetSocketAddress.createUnresolved()
to skip looking up the host in DNS:
public static InetSocketAddress createUnresolved ( String host , int port )
InetSocketAddress has a few getter methods you can use to inspect the object:
public final InetAddress getAddress ()
public final int getPort ()
public final String getHostName ()
Proxy Servers
The last constructor creates an unconnected socket that connects through a specified
proxy server:
public Socket ( Proxy proxy )
Normally, the proxy server a socket uses is controlled by the socksProxyHost and
socksProxyPort system properties, and these properties apply to all sockets in the sys‐
tem. However, a socket created by this constructor will use the specified proxy server
instead. Most notably, you can pass Proxy.NO_PROXY for the argument to bypass all
proxy servers completely and connect directly to the remote host. Of course, if a firewall
prevents direct connections, there's nothing Java can do about it; and the connection
will fail.
To use a particular proxy server, specify it by address. For example, this code fragment
uses the SOCKS proxy server at myproxy.example.com to connect to the host login.ibi‐
blio.org :
Search WWH ::




Custom Search