2007.09.21

Java模拟ping的程序

可以用于检测某个ip地址是否可以ping通,网上找的,可以直接运行.

  1. package com.demo;
  2.  
  3. import java.io.*;
  4.  
  5. public class ping
  6. {
  7.     public static void main(String [] args)
  8.     {
  9.         System.out.println(pingServer("localhost",100));
  10.     }
  11.  
  12.     /**  
  13.     * ping the server  
  14.     * @param server String  
  15.     * @param timeout int  
  16.     * @return boolean  
  17.     * @throws IOException  
  18.     */  
  19.     public static boolean pingServer(String server,int timeout)  
  20.     {  
  21.       BufferedReader in = null;  
  22.       Runtime r = Runtime.getRuntime();  
  23.    
  24.       String pingCommand = "ping " + server + " -n 1 -w " + timeout;  
  25.       try  
  26.       {  
  27.           Process p = r.exec(pingCommand);  
  28.           if (p == null)  
  29.           {  
  30.             return false;  
  31.           }  
  32.           in = new BufferedReader(new
  33.                  InputStreamReader(p.getInputStream()));  
  34.           String line = null;  
  35.           while ( (line = in.readLine()) != null)  
  36.           {  
  37.             if (line.startsWith("Reply from"))  
  38.             {  
  39.               return true;  
  40.             }
  41.             System.out.println(line);
  42.           }  
  43.           in.close();  
  44.       }  
  45.       catch (Exception ex)  
  46.       {  
  47.           ex.printStackTrace();
  48.           return false;  
  49.       }  
  50.       return false;  
  51.     }  
  52.    
  53. };

,

相关文章

引用地址:http://t263.net/93.html

欢迎发表评论