ssayyed
ssayyed

Reputation: 796

Java Socket... how it works?

I have a question on Java sockets.

I'm trying to build a basic server-client connection in java using the net package classes. so to start with, I'm used the Socket class and created a socket attached to what will be the client using

address= InetAddress.getByName(ip); socket = new Socket(address , port );

ip: is just a string representation of the ip address and port is a port number I specified to attach the socket to.

Now my question is, when I use the method getLocalPort() I get a different port number than the one I specified.Also, when I use the command 'netstat' on the command prompt I don't find the port number at which the socket is connected to in the list of active connections.

can anybody explain why is that?

Upvotes: 0

Views: 321

Answers (2)

user207421
user207421

Reputation: 310860

port is a port number I specified to attach the socket to

No it isn't. It is the remote port number to connect the socket to. One of the problems in your question is that you are using terminology incorrectly and therefore confusing yourself.

when I use the method getLocalPort() I get a different port number than the one I specified.

No you didn't. You specified the remote port when creating the Socket. getLocalPort() returns the local port. They aren't the same thing. There is a way to specify a local port number as well, but you don't need it. That process is calling 'binding'. Neither 'bind' nor 'connect' is an 'attach'.

Also, when I use the command 'netstat' on the command prompt I don't find the port number at which the socket is connected to in the list of active connections.

You should. You should see a line with the remote IP:port in the remote column, and the state as ESTABLISHED.

Upvotes: 1

musical_coder
musical_coder

Reputation: 3896

That's because the port number you specify in new Socket(address , port ); is the remote port number. For example, if your remote server had a socket open on port 8123 you wanted to connect to, you'd enter new Socket(address , 8123);.

The port number you're seeing in getLocalPort() and in netstat is the port number auto-generated for your local machine socket.

Upvotes: 1

Related Questions