java在linux下ping功能实现
import java.io.*;
public class Ping
{
public static void main(String [] args)
{
System.out.println(pingServer("www.baidu.com"));
}
/**
* ping the server
* @param server String
* @param timeout int
* @return boolean
* @throws IOException
*/
public static boolean pingServer(String server)
{
BufferedReader in = null;
Runtime r = Runtime.getRuntime();
boolean iFlag = false;
String pingCommand = "ping "+"-c2 " + server ;
System.out.println(pingCommand);
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.contains("64 bytes from"))
{
iFlag=true;
}
System.out.println(line);
}
in.close();
}
catch (Exception ex)
{
ex.printStackTrace();
return false;
}
return iFlag;
}
};