Java實現判斷某臺主機上的某個服務是否線上
程式碼如下:
package uestc.cn;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
public class testPort {
static String host_ip=null;
public static void main(String args[]){
String host[]={"192.168.1.111","192.168.1.103","192.168.1.112"};
int port = 27016;
testPort a= new testPort();
for(int i = 0;i<host.length;i++){
boolean stat = a.isConnect(host[i], port);
if(stat){
host_ip=host[i];
System.out.println(host_ip);
break;
}
}
}
public boolean isConnect(String host,int port){
Socket socket = new Socket();
try{
socket.connect(new InetSocketAddress(host, port));
}catch (IOException e) {
System.out.println("fail");
//e.printStackTrace();
return false;
}finally{
try{
socket.close();
}catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
}
經測試,可以執行