JAVA實現查看端口是否被佔用

public static void main(String[] args) {
boolean flag=false;
flag=isPortAvailable(ReadPropertiesUtil.OpenOffice_PORT);
if(flag){
System.out.println("未被佔用");
}else{
System.out.println("已佔有");
}
}
/**
* 查看端口是否被佔用
* @param port
* @return
*/
@SuppressWarnings("unused")
public static boolean isPortAvailable(int port) {
Socket s = new Socket();
boolean flag=false;
String f="";
List<String> ipList=new ArrayList<String>();
try {
Enumeration<NetworkInterface> netInterfaces = NetworkInterface
.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface nif = netInterfaces.nextElement();
Enumeration<InetAddress> iparray = nif.getInetAddresses();
while (iparray.hasMoreElements()) {
ipList.add(iparray.nextElement().getHostAddress());
}
}

for (int i = 0; i < ipList.size(); i++) {
flag=bindPort(ipList.get(i), port);
if(!flag){
break;
}
}

if(flag){//未被佔用
return true;
}else{//已被佔用
return false;
}
} catch (Exception e) {
return false;
}
}

/**
* 查看是否能綁定ip端口
* @param host
* @param port
* @return
* @throws Exception
*/
@SuppressWarnings("finally")
private static Boolean bindPort(String host, int port) throws Exception {
boolean flag=false;
try {
Socket s = new Socket();
s.bind(new InetSocketAddress(host, port));
s.close();
flag=true;
} catch (Exception e) {
flag=false;
e.printStackTrace();
} finally{
return flag;
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章