stdout
stdout

Reputation: 2651

HTTPURLConnection port number assignment

I was working with HTTPURLConnection and wondered how the port issues handled ? I mean the class uses sockets under the hood but how the client socket's port number is assigned internally? Any ideas ?

Thx

Upvotes: 1

Views: 1797

Answers (2)

piet.t
piet.t

Reputation: 11911

When creating a socket you have to take into account whether you want to open a server-socket or a client-socket.

A server-socket is opend and sits there waiting for an incoming request to start a "conversation". So it needs a port-number that is known to the client. For this reason several services have "well-known ports" like HTTP is port 80 etc.

A client-socket is created an starts with contacting a server-socket. In this case the server does not need to know the clients port-number in advance - it will receive it with the first incoming request. So when opening a client-socket the operating system will just choose a random port from a list of unused ports (look up "ephemeral port") and often close it once the conversation is finished.

The situation is similar to ip-adresses: the client needs to know the servers ip-address to contact it but the server does not need to know each clients ip-address.

Upvotes: 2

user207421
user207421

Reputation: 310840

It isn't. It is left entirely up to the operating system.

Upvotes: 3

Related Questions