"I want to make sure that when I re-run my application , any existing connections to these ports are removed."
The connections cannot stay open when your application exits - there is no process for them to be connected to. So in that sense, you don't have to worry about closing them on next launch.
"And is there a way to automatically close a connection when I am using InetAddress, which does not seem to have any method to terminate an existing connection to an address ?"
Yes - the connection will close when isReachable
is responded to, or when the timeout expires (or some other error occurs). Just creating an InetAddress
does not create a connection - it automatically creates and destroys them as needed to do its functionality. Connections are generally just short lived things that don't stay open unless you make them.