六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 83|回复: 0

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

[复制链接]

升级  73.33%

40

主题

40

主题

40

主题

秀才

Rank: 2

积分
160
 楼主| 发表于 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两种情况
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表