package shop.alien.util.ip;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * 测试ip连接状态
 *
 * @author ssk
 */
public class IpConnectTestUtil {

    public static void main(String[] args) {
        ipTest("34.80.132.13", 443);
    }

    /**
     * ip测试
     *
     * @param hostName ip地址
     * @param port     端口号
     * @return {true:成功;false:失败}
     */
    public static Boolean ipTest(String hostName, int port) {
        Socket socket = new Socket();
        try {
            //建立连接
            socket.connect(new InetSocketAddress(hostName, port), 5 * 1000);
            //通过现有方法查看连通状态
            boolean conn = socket.isConnected();
            //true为连通
            System.out.println("ip测试状态:" + conn);
            return conn;
        } catch (IOException e) {
            //当连不通时，直接抛异常，异常捕获即可
            System.err.println("ip测试状态:false");
            return false;
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                System.err.println("关闭ip测试失败");
            }
        }
    }
}
