java开发ping一个地址,返回是否连通

java开发ping一个地址,返回是否连通

package com.hk.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class PingTest {
    public static boolean pingServer(String server, int timeout)
    {
        BufferedReader in = null;
        Runtime r = Runtime.getRuntime();
       
        String pingCommand = "ping " + server + " -n 1 -w " + timeout;
        try
        {
            Process p = r.exec(pingCommand);
            if (p == null)
            {
                return false;
            }
            in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null)
            {
                if (line.startsWith("Reply from"))
                {
                    return true;
                }
            }
           
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            return false;
        }
        finally
        {
            try
            {
                in.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return false;
    } 
}

你可能感兴趣的:(Java)