Java Reference
In-Depth Information
Listening
Listening
Established
Established
Local port
99
Local port
99
Local port
99
Local port
1025
Local IP
*
Local IP
10.1.2.3
Local IP
192.168.3.2
Local IP
10.1.2.3
Remote port
*
Remote port
*
Remote port
30001
Remote port
25
Remote IP
*
Remote IP
*
Remote IP
172.16.1.9
Remote IP
10.5.5.8
0
1
2
Figure 5.12: Demultiplexing with multiple matching sockets.
For example, consider a host with two IP addresses, 10.1.2.3 and 192.168.3.2, and with a
subset of its active TCP socket structures, as shown in Figure 5.12. The structure labeled 0 is
associated with a ServerSocket and has port 99 with a wildcard local address. Socket structure 1
is also for a ServerSocket on the same port, but with the local IP address 10.1.2.3 specified (so
it will only accept connection requests to that address). Structure 2 is for a connection that
was accepted via the ServerSocket for structure 0, and thus has the same local port number,
but also has its local and remote Internet addresses filled in. Other sockets belong to other
active connections. Now consider a packet with source IP address 172.16.1.10, source port
56789, destination IP address 10.1.2.3, and destination port 99. It will be delivered to the
socket associated with structure 1, because that one matches with the fewest wildcards.
When a program attempts to create a socket with a particular local port number, the
existing sockets are checked to make sure that no socket is already using that local port. A
Socket() constructor will throw an exception if any socket matches the local port and local IP
address (if any) specified in the constructor. This can cause problems in the following scenario:
1. A client program creates a Socket with a specific local port number, say,
P
, and uses it to
communicate with a server.
2. The client closes the Socket , and the underlying structure goes into the Time-Wait state.
3. The client program terminates and is immediately restarted.
If the new incarnation of the client attempts to use the same local port number, the Socket
constructor will throw an IOException , because of the other structure in the Time-Wait state.
As of this writing, the only way around this is to wait until the underlying structure leaves the
Time-Wait state.
So what determines the local/foreign address/port? For a ServerSocket , all constructors
require the local port. The local address may be specified to the constructor; otherwise, the
local address is the wildcard (*) address. The foreign address and port for a ServerSocket are
always wildcards. For a Socket , all constructors require specification of the foreign address
and port. The local address and/or port may be specified to the constructor. Otherwise, the
local address is the address of the network interface through which the connection to the
server is established, and the local port is a randomly selected, unused port number greater
Search WWH ::




Custom Search