javasockets

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?

Solution

  • 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.