JAVA测试IP端口能否ping通
程序员文章站
2024-03-20 11:50:58
...
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* @author qiufengliang
* @version 1.0
* @description
* @date 2020/4/1
*/
public class TestConnect {
/**
* 测试IP 端口 是否通
* @param host
* @param port
* @return
*/
private static boolean isHostPortReachable(String host,Integer port,Integer timeOut){
Boolean isConnect = false;
Socket connect = new Socket();
try {
InetSocketAddress inetSocketAddress = new InetSocketAddress(host, port);
connect.connect(inetSocketAddress, timeOut);
isConnect = connect.isConnected();
} catch (IOException e) {
}finally {
if (connect != null) {
try {
connect.close();
} catch (IOException e) {
}
}
}
return isConnect;
}
/**
* 测试IP是否通
* @param host
* @param timeOut 超时时间
* @return
*/
public static boolean isHostReachable(String host, Integer timeOut) {
try {
return InetAddress.getByName(host).isReachable(timeOut);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
public static void main(String[] args) {
System.out.println( isHostReachable("192.168.1.23",8080));
}
}