1

How do you know what is a valid port for you to select for the Socket object in java when creating a client?

For instance, I have tried Socket("localhost", 0).

However, I end up throwing an exception due to not being able to bind to the port.

I know that ServerSocket binds to any free port when port is 0. Is there a similar setting for the client when initializing the socket?

4
  • 1
    Client sockets listen to the same port that the Server is bound to. You got it the other way around. ServerSockets would associate a port to listen on and that port shouldn't be used at that time and not one of those ports used by the OS. Commented Apr 16, 2013 at 23:07
  • 1
    You need a ServerSocket if you want to listen on a port. Commented Apr 16, 2013 at 23:15
  • 1
    @asgs Client sockets don't 'listen' to anything. They connect to a server port. Commented Apr 17, 2013 at 0:09
  • @EJP, apologize the wrong word used above. I also meant to say Server listens to a port that the clients would connect to. Commented Apr 17, 2013 at 2:26

3 Answers 3

2

The client needs to know which port the server is listening on. There's a detailed explanation at What Is a Socket? and sample code at Reading from and Writing to a Socket.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you to clarify when "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." This port on the client does not have to == the port being listened on by the server right?
@user1431282 No, the local port that the client binds to is automatic and does not need to be the same one used on the server. I'm not even sure if you can control that.
2

From the JavaDocs:

public Socket(InetAddress address, int port)
       throws IOException

A string is not an InetAddress. Use InetAddress.getByName() to create an InetAddress from a string (make sure the string is the host-name of the website).


Note: you can't always choose freely which port to use, on some systems, there may be ranges that are reserved and considered off-limits to user applications.

Comments

1

That parameter specifies a target port to connect to, not a local port to bind to. The local port is allocated automatically, you don't have to worry about it. You do need to know what server port to connect to. Using zero for the target (connect) port is meaningless.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.