Java 實現Ping 功能__Java

來源:互聯網
上載者:User
package com.hotent.monitorRecords.dateReader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Pinger {
    /**  * 要ping的主機  */
    private String remoteIpAddress;
    /**  * 設定ping的次數  */
    private final int pingTimes;
    /**  * 設定逾時  */
    private int timeOut;
    /**  * 建構函式  *  * @param remoteIpAddress  * @param pingTimes  * @param timeOut  */
    public Pinger(String remoteIpAddress, int pingTimes, int timeOut) {  
        super();  
        this.remoteIpAddress = remoteIpAddress;  
        this.pingTimes = pingTimes;
        this.timeOut = timeOut;
    }


/**  * 測試是否能ping通  * @param server  * @param timeout  * @return  
 * @throws UnsupportedEncodingException */
public boolean isReachable() throws UnsupportedEncodingException {
        BufferedReader in = null;
        Runtime r = Runtime.getRuntime();
        // 將要執行的ping命令,此命令是windows格式的命令  
        String pingCommand = "ping " + remoteIpAddress + " -n " + pingTimes    + " -w " + timeOut;
        try {  
            // 執行命令並擷取輸出
            System.out.println(pingCommand);   
            Process p = r.exec(pingCommand);  
            if (p == null) {   
                return false;
            }   
            in = new BufferedReader(new InputStreamReader(p.getInputStream(),"GBK"));
            // 逐行檢查輸出,計算類似出現=23ms TTL=62字樣的次數   
            int connectedCount = 0;
            String line = null;
            while ((line = in.readLine()) != null) {
                String str=new String (line.getBytes("GB2312"),"GBK");
                System.out.println(str);
                //System.out.println("getCheckResult(line)=="+getCheckResult(line));
                connectedCount += getCheckResult(line);
            }   
            // 如果出現類似=23ms TTL=62這樣的字樣,出現的次數=測試次數則返回真  
            //System.out.println("connectedCount=="+connectedCount);
            return connectedCount == pingTimes;  
        
        } catch (Exception ex) {  
                ex.printStackTrace();  
                // 出現異常則返回假   
                return false;
        } finally {
            try {   
                in.close();
                } catch (IOException e) {  
                    e.printStackTrace();
                }
        }
    }
/**  * 若line含有=18ms TTL=16字樣,說明已經ping通,返回1,否則返回0.
 * *  * @param line  * @return  */
private static int getCheckResult(String line) {
        // System.out.println("控制台輸出的結果為:"+line);  
        Pattern pattern = Pattern.compile("(\\d+ms)(\\s+)(TTL=\\d+)",   
                Pattern.CASE_INSENSITIVE);
        //System.out.println("pattern.matcher(line)==="+pattern.matcher(line));
        Matcher matcher = pattern.matcher(line);
        //System.out.println("matcher==="+matcher);
        while (matcher.find()) {  
                return 1;  
            }
        return 0;
     }
public static void main(String[] args) {  
        Pinger p = new Pinger("192.168.2.171", 10, 5000);  
        try {
            System.out.println(p.isReachable());
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
    }
    
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.