views:

152

answers:

4

Hello; When a server accepts a client over a tcp/ip connection, a new socket is created.

Is it safe to use the LocalEndPoint port (from the client perspective) as an id? Example (from the server perspective):

int clientId = ((IPEndPoint)client.RemoteEndPoint).Port;

On my local machine, the port seems to be unique, but with multiple clients on different machines, it may not always be the case.

My second question: Let's say the port can't be used like a unique id, how the server (and hence the protocol stack) can differentiate between two client socket (from the server perspective).

TY.

A: 

Why not just use "client" as the unique identifier. A unique identifier need not be of a value type.

John Saunders
+2  A: 

The uniqueness of a socket is identified by 4 values: (local IP, local port,remote IP, remote port) and that's how the protocol stacks identify a connection.

Given this, you can have several connections from the same port number to same port number but e.g. to a different remote address. Typically you have to specifically request permissions to use the same local port for more than 1 outbound connection.

Your example int clientId = ((IPEndPoint)client.RemoteEndPoint).Port; doesn't use the local port, but the port on the remote end. This is certainly not unique, as different clients might happen to chose the same port. Your server port is probably fixed, and will always be the same for all connections. Thus if you want something unique on the server side, you have to use the 4 values mentioned above.

However if you only need a unique identifier within your own client application among connections you've set up yourself, the local port will do.

nos
Thanks to nos, Duck, John Saunders and divinci, all your answers are very good.it was very helpful. Thanks again.
+1  A: 

The short answer to the first question is probably no. The client OS will usually pick a port from a range. Even if that range is 40-50 thousand large, if your server is busy enough, sooner or later you may have the same port coming in from different clients. If it isn't a busy server you may get lucky.

Sockets are differentiated from each other based on pairs of address/port/protocol. The combined set of these values from the client and server will be unique.

Why can't you just use the client address and port as a temporary id?

Duck
A: 

Hi Mat,

Don't use the remote end point - create a GUID - for each (accepted)connection.

Pass the GUID back to the client socket - get the client to save it (much better than a HTTP session) and add the GUID to any subsequent HTTP headers directed at you :)

then!! the perfect need for a HastTable<> !!! only a couple of situations I know of!

divinci