Re: Java Socket Programming



On 30 Mar 2006 22:12:05 -0800, DaveL wrote:
Socket[addr=65.93.27.235,port=61159,localport=8000]
Socket[addr=127.0.0.1,port=1597,localport=8000]
Socket[addr=70.28.249.97,port=2074,localport=8000]

From the output above, it appears all client socket connections are
connected on my localport=8000. Is this the correct behavious that I
should be expecting?

I would like to think that the "new Sockets" returned by "accept( )"
would be bound on a different available port than the one that
SimpleServer is listening on, but apparently that isn't the case.

First, consider this:

Socket s = new Socket(rhost, 8000); // connect to port 8000
int rport = s.getPort(); // check remote port

if (rport != 8000) {
System.out.println("Suspicious");
}

Are you suggesting that the result of connecting to a given port
number *shouldn't* result in a connection to that same port number?

What happens is that the Socket created in the call to accept() is a
clone of the ServerSocket, and it inherits several attributes from the
ServerSocket, including the port number.

The reason this works is that each connection is uniquely identified
by 4 attributes: the local address and local port number, and the
remote address and remote port number.

The remote addr and port for the ServerSocket are wildcards, since it
isn't connected. The resulting connected Socket has these bound to the
addr and port of the client's connecting Socket, so the ServerSocket
and all Sockets created from it are unique and distinct, regardless of
the local address and port.

Two Sockets cannot be identical in all 4 of the attributes, so for
example it isn't possible to create two ServerSockets listening on the
same port, unless you also bind them to different local addresses
(which requires you to have multiple local addresses to bind to).

/gordon

--
[ do not email me copies of your followups ]
g o r d o n + n e w s @ b a l d e r 1 3 . s e
.