hedfun2
hedfun2

Reputation: 33

Have socket connect to SeverSocket(0) without port forwarding?

I'm trying to make a simple messaging program in java that can work as long as you are connected to the internet. In order to do so I need to make a ServerSocket to receive the message. But in order to make a ServerSocket I need to assign it to a port. If I assign it a specific port such as 25504, how would a client connect to that server without having to port forward that port? And if I use ServerSocket(0) to find a free port, how would the client know what port it found without the server sending the client the port? I want this program to be able to be used without having to port forward so you can use it in public places.

Upvotes: 1

Views: 1588

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595412

You don't need a server socket just to receive messages. A client socket can connect to a server and then receive messages just as easily. Connecting a client to a server does not require any port forwarding on the client side.

However, if you do use a server socket, and you are running behind a network router, you have to configure port forwarding, there is no avoiding that. However, many routers support uPNP, which (amongst other things) can allow an app to dynamically open/close forwarding ports on the router.

If you bind a server socket to port 0 to select a random ephemeral port, then you must publish that port somewhere that a client can find it, whether that be on a remote site, or discoverable through network subnet queries, etc.

Upvotes: 2

Related Questions