通过Java代码实现ping功能测试ip地址与ip:port的连通性

通过Java代码实现测试ip地址与ip:port的连通性

  • 需求分析
  • 具体实现
    • 测试ip连通性
    • 测试ip:port连通性
    • 重试机制

需求分析

最近在业务中,需要添加一种掉线告警系统。

大致思路为:

通过定时任务扫描,每一个小时判断一次设备是否在线,如果在线继续判断端口是否能够通讯。如果不在线或者不能通讯,需要及时push消息给告警人员,及时处理。

具体实现

测试ip连通性

主要通过InetAddress类来实现

 /**
     * @param ipAddress 待检测IP地址
     * @param timeout   检测超时时间(超时应该在3钞以上)
     * @return
     */
    public Boolean ipDetection(String ipAddress, Integer timeout) {
        // 当返回值是true时,说明host是可用的,false则不可。
        boolean status = false;
        try {
            status = InetAddress.getByName(ipAddress).isReachable(timeout);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return status;
    }

测试ip:port连通性

主要通过socket发送InetSocketAddress包装的ip与端口号实现

 /**
     * 通过socket检测ip:port是否能够通信
     *
     * @param ipAddress
     * @param port
     * @param timeout
     * @return
     */
    public Boolean ipDetection(String ipAddress, Integer port, Integer timeout) {
        Socket socket = new Socket();
        try {
            socket.connect(new InetSocketAddress(InetAddress.getByName(ipAddress), port), timeout);
        } catch (IOException e) {
            return false;
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

重试机制

/**
     * @param ipAddress  待检测IP地址
     * @param port       待检测port
     * @param retryCount 重试次数
     * @param timeout    检测超时时间(超时应该在3钞以上)
     * @param detectionFlag   标志位 0检测IP  1检测IP:PORT
     * @return
     */
    public Boolean retryIPDetection(String ipAddress, Integer port, Integer retryCount, Integer timeout, Integer detectionFlag) {
        // 当返回值是true时,说明host是可用的,false则不可。
        boolean status = false;
        Integer tryCount = 1;

        //重试机制
        while (tryCount <= retryCount && status == false) {
            if (detectionFlag.equals(0)) {
                status = ipDetection(ipAddress, timeout);
            } else {
                status = ipDetection(ipAddress, port, timeout);
            }
            if (status == false) {
                log.info("第[" + tryCount + "]次连接 " + ipAddress + ":" + port + " 失败!");
                tryCount++;
                continue;
            }
            log.info("连接 " + ipAddress + ":" + port + " 成功!");
            return true;
        }
        return false;
    }

你可能感兴趣的:(业务代码,java,功能测试)