javavsnet 发表于 2013-2-7 03:45:06

判断端口是否被占用的方法

在glassfish的NetUtils中,是这样判断的
try {ServerSocket ss = new ServerSocket(port);ss.close();return true;} catch (Exception e) {return false;}
这样判断有问题,如果一个端口被应用占用了,binding的地址是192.168.0.251:port
这个程序是判断不出端口port被占用的。因为ServerSocket ss = new ServerSocket(port);去binding的地址是0.0.0.0:port,而不是192.168.0.251:port,在windows上是可以binding的,不能判断出端口已经被占用。
这里改为
private static void bindPort(String host, int port) throws Exception{            Socket s = new Socket();            s.bind(new InetSocketAddress(host, port));            s.close();      }……try {                  bindPort("0.0.0.0", port);                  bindPort(InetAddress.getLocalHost().getHostAddress(),port);return true;} catch (Exception e) {return false;}
这样就检测了0.0.0.0和本机ip两种情况
页: [1]
查看完整版本: 判断端口是否被占用的方法