The java.net.ServerSocket
class has three constructors
that let you specify the port to bind to, the queue length for
incoming connections, and the IP address to bind to:
public ServerSocket(int port) throws IOException
public ServerSocket(int port, int backlog) throws IOException
public ServerSocket(int port, int backlog, InetAddress bindAddr)
throws IOException
Normally you only specify the port you want to listen on, like this:
try {
ServerSocket ss = new ServerSocket(80);
}
catch (IOException ex) {
System.err.println(ex);
}
When you create a ServerSocket
object, it attempts to
bind to the port on the local host given by the port argument. If
another server socket is already listening to the port, then a
java.net.BindException
, a subclass of
java.io.IOException
, is thrown. No more than one process or
thread can listen to a particular port at a time. This includes
non-Java processes or threads. For example, if there's already an
HTTP server running on port 80, you won't be able to bind to port
80.
On Unix systems (but not Windows or the Mac) your program must be running as root to bind to a port between 1 and 1023.
0 is a special port number. It tells Java to pick an available
port. You can then find out what port it's picked with the
getLocalPort()
method. This is useful if the client and the
server have already established a separate channel of communication
over which the chosen port number can be communicated.
For example, the ftp protocol uses two sockets. The initial connection is made by the client to the server to send commands. One of the commands sent tells the server the name of the port on which the client is listening. The server then connects to the client on this port to send data.
try {
ServerSocket ftpdata = new ServerSocket(0);
int port = ftpdata.getLocalPort();
}
catch (IOException ex) {
System.err.println(ex);
}