public static boolean pingIp(String ip) throws UnknownHostException, IOException {
        //能ping通放回true 反之 false 超时时间 3000毫秒
        return InetAddress.getByName(ip).isReachable(5000);
    }
 
    public static boolean telnetport(String ip, Integer port) throws IOException {
        Socket connect = new Socket();
        boolean res = false;
        try {
            connect.connect(new InetSocketAddress(ip, port), 1000);//建立连接
            //能telnet通返回true,否则返回false
            res = connect.isConnected();//通过现有方法查看连通状态
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("false");//当连不通时,直接抛异常,异常捕获即可
        } finally {
            try {
                connect.close();
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("false");
            }
        }
        return res;
    }

 

package com.javabasic.io;

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

/**
 * @Description 测试ip及端口连通性
 * @ClassName NetUtils
 * @Author yuhuofei
 * @Date 2022/3/13 17:03
 * @Version 1.0
 */
public class NetUtils {

    /**
     * 测试ip及端口连通性
     *
     * @param host
     * @param port
     * @param timeout
     * @return boolean
     */
    public static boolean testIpAndPort(String host, int port, int timeout) {
        Socket s = new Socket();
        boolean status = false;
        try {
            s.connect(new InetSocketAddress(host, port), timeout);
            System.out.println("ip及端口访问正常");
            status = true;
        } catch (IOException e) {
            System.out.println(host + ":" + port + "无法访问!");
        } finally {
            try {
                s.close();
            } catch (IOException ex) {
                System.out.println("关闭socket异常" + ex);
            }
        }
        return status;
    }

	//测试方法
    public static void main(String[] args) {
        String host = "127.0.0.1";
        int port = 8080;
        int timeOut = 3000;
        testIpAndPort(host, port, timeOut);
    }
}