Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Socket - Local Port

Tags:

java

sockets

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

like image 313
A.B. Avatar asked Nov 21 '12 23:11

A.B.


People also ask

What is local port in socket?

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.

Is java socket TCP or UDP?

Java provides the reliable stream-based communication for TCP as well as the unreliable datagram communication for UDP. The socket API in Java is provided in the java.net package which has several classes supporting socket-based client/server communication.

What is socket and port in java?

A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to. An endpoint is a combination of an IP address and a port number.


1 Answers

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.

like image 196
ShyJ Avatar answered Oct 11 '22 20:10

ShyJ