Constructing Socket Objects

There are four public, non-deprecated constructors in the Socket class. (There are also two protected constructors and two deprecated constructors I won't discuss.)

 public Socket(String host, int port) throws UnknownHostException, IOException
 public Socket(InetAddress address, int port) throws IOException
 public Socket(String host, int port, InetAddress localAddr, int localPort) 
  throws IOException
 public Socket(InetAddress address, int port, InetAddress localAddr, int localPort) 
  throws IOException

You need to at least specify the remote host and port you want to connect to. The host may be specified as either a string like "utopia.poly.edu" or as an InetAddress object. The port should be an int between 1 and 65535. For that matter it should be a particular one. You need to know the port just as much as the hostname. For example,

Socket webSunsite = new Socket("metalab.unc.edu", 80);

The latter two constructors also specify the host and port you're connecting from. On a system with multiple IP addresses, like many web servers, this allows you to pick your network interface and IP address. You can also specify a port number, but since any particular port may be occupied you should probably set the port number to 0 instead. This tells the system to randomly choose an available port. If you need to know the port you're connecting from, you can always get it with getLocalPort().

Socket metalab = new Socket("metalab.unc.edu", 80, "calzone.oit.unc.edu", 0);

The Socket() constructors do not just create a Socket object. They also attempt to connect the underlying socket to the remote server. All the constructors throw an IOException if the connection can't be made for any reason.


Previous | Next | Top | Cafe au Lait

Copyright 1997, 1999 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified December 16, 1999