Question

Is there a simple way to make sure that a local port is not already open. Some TCP socket servers (eg Grizzly) don't seem to do this check by default. When this check is missing, the server appears to start and respond, but the client code is just connecting to an old server that wasn't shutdown. This can be very bad!

Is there a simple line of Java code that could check to be sure that port isn't already used by another process?

Was it helpful?

Solution

I see two obvious ways to do it:

  1. try to connect to that port on localhost, if you get accepted, the the port is being used
  2. try to open a ServerSocket in listen mode in that port. If you get "already bound" exception, then the port is being used

Hope it helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top