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?

Table of Contents

 About This JDK Tutorial Book

 JDK (Java Development Kit)

 Java Date-Time API

 Date, Time and Calendar Classes

 Date and Time Object and String Conversion

 Number Object and Numeric String Conversion

 Locales, Localization Methods and Resource Bundles

 Calling and Importing Classes Defined in Unnamed Packages

 HashSet, Vector, HashMap and Collection Classes

 Character Set Encoding Classes and Methods

 Character Set Encoding Maps

 Encoding Conversion Programs for Encoded Text Files

 Java Logging

Socket Network Communication

 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

 Datagram Network Communication

 DOM (Document Object Model) - API for XML Files

 SAX (Simple API for XML)

 DTD (Document Type Definition) - XML Validation

 XSD (XML Schema Definition) - XML Validation

 XSL (Extensible Stylesheet Language)

 Message Digest Algorithm Implementations in JDK

 Private key and Public Key Pair Generation

 PKCS#8/X.509 Private/Public Encoding Standards

 Digital Signature Algorithm and Sample Program

 "keytool" Commands and "keystore" Files

 KeyStore and Certificate Classes

 Secret Key Generation and Management

 Cipher - Encryption and Decryption

 The SSL (Secure Socket Layer) Protocol

 SSL Socket Communication Testing Programs

 SSL Client Authentication

 HTTPS (Hypertext Transfer Protocol Secure)

 Outdated Tutorials

 References

 Full Version in PDF/EPUB