Windows下使用JAVA检测端口是否已被占用
2013-07-12 14:44
961 查看
第一种方法:使用Socket
public boolean isPortUsing(String hostIp,int port){
boolean flag = false;
try {
InetAddress address = InetAddress.getByName(hostIp);
new Socket(address,port);
flag = true;
} catch (UnknownHostException e) {
}catch (IOException e) {
System.out.println("the port cannot be connected!");
}
return flag;
}
第二种方法:使用dos命令
public boolean isPortRunning(String port){
try {
Process process = Runtime.getRuntime().exec("cmd /c netstat -an | findstr "+port);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String lineString = "" ;
boolean flag = false;
while ((lineString = reader.readLine()) != null) {
flag = regexFind(lineString, port);
if(flag){
return flag;
}
}
} catch (IOException e) {
}
return false;
}
public boolean regexFind(String lineString,String port){
String regex=":(\\d+)\\s+\\d+";
Matcher matcher = Pattern.compile(regex).matcher(lineString);
while(matcher.find()){
if(port.trim().equals(matcher.group(1).trim())){
return true;
}
}
return false;
}
public boolean isPortUsing(String hostIp,int port){
boolean flag = false;
try {
InetAddress address = InetAddress.getByName(hostIp);
new Socket(address,port);
flag = true;
} catch (UnknownHostException e) {
}catch (IOException e) {
System.out.println("the port cannot be connected!");
}
return flag;
}
第二种方法:使用dos命令
public boolean isPortRunning(String port){
try {
Process process = Runtime.getRuntime().exec("cmd /c netstat -an | findstr "+port);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String lineString = "" ;
boolean flag = false;
while ((lineString = reader.readLine()) != null) {
flag = regexFind(lineString, port);
if(flag){
return flag;
}
}
} catch (IOException e) {
}
return false;
}
public boolean regexFind(String lineString,String port){
String regex=":(\\d+)\\s+\\d+";
Matcher matcher = Pattern.compile(regex).matcher(lineString);
while(matcher.find()){
if(port.trim().equals(matcher.group(1).trim())){
return true;
}
}
return false;
}
相关文章推荐
- java检测本机端口是否已经被使用的代码
- C#网络/检测某端口是否被占用的方法
- java检测端口号是否被占用
- ZooKeeper之Java客户端API使用—检测节点是否存在
- 使用nc检测udp端口是否可以正常通讯 【转】
- linux 与windows netstat命令查看端口是否占用
- windows和linux中检查端口是否被占用
- 使用nc检测udp端口是否可以正常通讯
- windows下查看端口是否被占用
- nsclient使用nrpe的方法 + windows检测端口的bat脚本
- windows下查看某端口是否被占用
- 使用Java开发自动化检测域名是否可注册工具 推荐
- C#检测端口是否被占用(转帖)
- 使用java代码关闭指定端口的程序-windows
- windows和linux中检查端口是否被占用
- windows下查看端口是否被占用
- windows和linux中检查端口是否被占用
- JAVA检测端口的占用情况
- 使用Socket判断端口是否被占用
- 怎么在windows下查看"80"端口是否被占用