tags:

views:

330

answers:

1

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?

+3  A: 

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.

Pablo Santa Cruz
Between the two of these, probably better to try connecting -- opening a port is more likely to pop up a user's firewall with warning about "Application XYZ is trying to listen on port 1234..."
Mark Rushakoff
ServerSocket solution was quite slick. The firewall popup is fine since the program will provide a service on that port anyway. Thanks for your help.
User1
Just a note: If you try to connect to a port and fail, it might be because you are firewalled from connecting to that port. Just because YOU can't connect doesn't mean it's not in use.
Mr. Shiny and New
@Mr. Shiny and New: true. But he was talking about a local, not a remote port. In that case, the odds of not being able to connect to that port if it is indeed opened, using "localhost" as hostname, are minimal.
Pablo Santa Cruz
@Mark Rushakoff: It's not better to try connecting as that can have unpredictable results. In fact you are never guaranteed response when trying to connect. So at best you have an indication that there is nothing running, but the only way to be sure is to try to bind to the port and either you get an exception or you succeed.
andy