求助!怎样用JAVA判断IP是否有通!!!返回值是true或false

解决方案 »

  1.   

    import java.io.BufferedReader;   
    import java.io.IOException;   
    import java.io.InputStream;   
    import java.io.InputStreamReader;   
      
      
    public class TestPing {   
        public static String testIP(String strip) {   
            String message = null;   
            Runtime runtime = Runtime.getRuntime();   
            Process process = null;   
            String line = null;   
            InputStream is = null;   
            InputStreamReader isr = null;   
            BufferedReader br = null;   
            String ip = strip;   
            try {   
                // 根据CMD去PING IP   
                process = runtime.exec("ping  " + ip + " -w 1");   
                is = process.getInputStream();   
                isr = new InputStreamReader(is);   
                br = new BufferedReader(isr);   
                while ((line = br.readLine()) != null) {   
                    if ("Request timed out.".equals(line)   
                            || (line.length() > 3 && (line.trim()   
                                    .indexOf("Ping request could not")) >= 0)) {   
                        message = "机器IP有错!";   
                    }   
                    System.out.println(line);   
                }   
                br.close();   
                isr.close();   
                is.close();   
            } catch (IOException e) {   
                e.printStackTrace();   
            }   
            return message;   
        }   
           
        public static void main(String[] args){   
            String result=TestPing.testIP("192.168.0.100");   
            System.out.println(result);   
        }   
    }