JAVA測試IP端口能否ping通

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章