问题
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?
回答1:
I see two obvious ways to do it:
- try to connect to that port on localhost, if you get accepted, the the port is being used
- 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.
来源:https://stackoverflow.com/questions/1765235/checking-a-local-tcp-port-is-not-open-in-java