JDK (Java Development Kit) Tutorials
Dr. Herong Yang, Version 5.00

Binding Sockets to Specific Ports

This section describes how to bind a socket to a specific port. Binding multiple client sockets to the same port is not allowed.

As I mentioned previously, I used a special socket constructor to allow the system to bind the socket an un-specified local address and port number. This gives the system the freedom to pickup an un-used port number. If I change SocketClient.java from:

         Socket c = new Socket("localhost",8888);

to:

         Socket c = new Socket();
         c.bind(new InetSocketAddress("localhost",4444));
         c.connect(new InetSocketAddress("localhost",8888));

the first running instance of SocketClient will work, but additional running instances will get the following error:

java.net.BindException: Address already in use: JVM_Bind

Why? Because, at any given time, only one socket can be bound to a given port.

So, allowing the system to pick up a free local port number is a better idea.

However, the sockets created by the ServerSocket.accept() method seems to be allowed to bind to the same local port. See the output of ReverseEchoServer. When two or more client programs are connected to it, sockets created for the connections are all bound to the same port number, 8888.

Exercise: Can you re-bind a bound socket to new port number?

Last update: 2006.

Sections in This Chapter

What Is a Socket?

Establishing a Socket Communication Link

ReverseEchoer.java - A Simple Server Socket Application

SocketClient.java - A Simple Client Socket Application

ReverseEchoServer.java - A Multi-Connection Socket Server

Binding Sockets to Specific Ports

Dr. Herong Yang, updated in 2008
Binding Sockets to Specific Ports