Chathuranga Chandrasekara
Chathuranga Chandrasekara

Reputation: 20906

How do I close a port in a case of program termination?

I am using Socket communication in one of my Java applications.As I know if the program meets any abnormal termination the listening ports does not get closed and the program cannot be started back because it reports "Port already open.." Do I have anyway to handle this problem? What is the general way used to handle this matter?

Upvotes: 9

Views: 15556

Answers (4)

James Davies
James Davies

Reputation: 9859

You want to set the SO_REUSEADDR flag on the socket.

See setReuseAddress().

Upvotes: 4

Greg Hewgill
Greg Hewgill

Reputation: 993105

It sounds like your program is listening on a socket. Normally, when your program exits the OS closes all sockets that might be open (including listening sockets). However, for listening sockets the OS normally reserves the port for some time (several minutes) after your program exits so it can handle any outstanding connection attempts. You may notice that if you shut down your program abnormally, then come back some time later it will start up just fine.

If you want to avoid this delay time, you can use setsockopt() to configure the socket with the SO_REUSEADDR option. This tells the OS that you know it's OK to reuse the same address, and you won't run into this problem.

You can set this option in Java by using the ServerSocket.setReuseAddress(true) method.

Upvotes: 23

VonC
VonC

Reputation: 1324347

As mentioned in the Handling abnormal Java program exits, you could setup a Runtime.addShutdownHook() method to deals with any special case, if it really needs an explicit operation.

Upvotes: 2

Esko Luontola
Esko Luontola

Reputation: 73625

The operating system should handle things such as that automatically, when the JVM process has ended. There might be a short delay before the port is closed, though.

Upvotes: 2

Related Questions