Checking a local TCP port is not open in Java

大憨熊 提交于 2019-12-12 01:34:37

问题


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:

  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.



来源:https://stackoverflow.com/questions/1765235/checking-a-local-tcp-port-is-not-open-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!