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

判断网络IP端口是否可连接

程序员文章站 2022-03-26 15:35:36
...
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

public class ConnectionUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionUtils.class);

    private static final int TIMEOUT = 3000;

    public static void main(String[] args) {
        System.out.println(isReachable("192.168.43.103"));
        System.out.println(isConnectable("192.168.43.103", 8081));
    }

    public static boolean isReachable(String ip) {
        if (StringUtils.isBlank(ip)) {
            return false;
        }
        try {
            return InetAddress.getByName(ip).isReachable(TIMEOUT);
        } catch (Exception e) {
            LOGGER.info("isReachable({}) encoutered exception :{}", ip, e);
        }
        return false;
    }

    public static boolean isConnectable(String ip, int port) {
        if (StringUtils.isBlank(ip) || port < 0) {
            return false;
        }
        Socket socket = new Socket();
        InputStream inputStream = null;
        try {
            socket.setSoTimeout(TIMEOUT);
            socket.connect(new InetSocketAddress(ip, port));
            inputStream = socket.getInputStream();
            byte[] b = new byte[1024];
            int size;
            while (true) {
                size = inputStream.read(b);
                if (-1 == size) {
                    break;
                }
            }
        } catch (Exception e) {
            LOGGER.info("isConnectable({},{}) encoutered exception :{}", ip, port, e);
            String message = e.getMessage();
            System.out.println(message);
            if (StringUtils.isNotBlank(message) && (message.lastIndexOf("Connection refused") != -1 || message.lastIndexOf("Connection timed out") != -1)) {
                return false;
            }

        } finally {
            try {
                socket.close();
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {

            }
        }
        return true;
    }
}