A.B.
A.B.

Reputation: 2470

Java Socket - Local Port

I'm learning the socket programming with Java. I connect to a website using this statement:

s = new Socket("www.nba.com", 80);

When i debug the application and look at the content of s, i see:

Socket[addr=www.nba.com/2.21.246.97,port=80,localport=7846]

1) I want to know where this localport 7846 comes from and what it exactly is.

2) if the IP address of the website is 2.21.246.97, why can't i connect to the website by just typing 2.21.246.97 in the address field of my browser ?


Thanks

Upvotes: 11

Views: 16466

Answers (2)

swayamraina
swayamraina

Reputation: 3158

local port is nothing but a socket descriptor (or a very high numbered port)

Whenever a process makes an API call, the request, via the kernel, creates a socket descriptor so as to bind (and identify) this particular request's response. Any outbound call results in a socket being created and when the response arrives at the NIC (network interface) and then to kernel, the kernel figures out the destination application for this response.

This is done by checking the port which has a ono-one mapping to the process running (pid). Then it checks the socket descriptor value attached in the response meta (this value is passed on when creating a connection) and sends the response stream to the socket buffer.

The CPU then wakes the process to collect the response.

So answering your main question,

  • local port is nothing but a socket descriptor
  • ideally if there is no virtualisation and you own the hardware, you should be able to. connect to it via ip. But generally that is not the case and a lot of NAT (network address translation) goes in which might prevent this

try, ls -li /proc/<pid>/fd/ to see all the open socket descriptors
where is your application process-id

Upvotes: 1

ShyJ
ShyJ

Reputation: 4650

It is a local socket port number. It is usually assigned by the system.

See What is a Socket?.

On the client-side: The client knows the hostname of the machine on which the server is running and the port number on which the server is listening. To make a connection request, the client tries to rendezvous with the server on the server's machine and port. The client also needs to identify itself to the server so it binds to a local port number that it will use during this connection. This is usually assigned by the system.

As to the second question:

I assume this IP address is what you get by your DNS server when you lookup www.nba.com (mine is different). The problem might be that the HTTP server at this address serves multiple virtual hosts and/or it cares about the Host header your browser sends. In your case it is the IP address instead of www.nba.com.

Upvotes: 9

Related Questions