欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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));
    }
}

 

相关标签: JAVA专栏