java判断ip及端口连通性

java判断一个ip及其端口能否正常访问

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

你可能感兴趣的:(Java,java)