局域网扫描IP

今天有朋友去面试,被问到一个“如何扫描局域网IP”的问题(即找出局域网中当前已使用的IP),朋友回答的不好,回来问我,我首先想到的就是使用ping命令将局域网可分配的IP地址逐个遍历一遍,能ping通的就是已使用的。

那么基于思路,实现代码也没啥太难的,以java语言来实现。

linux下的代码:

public static boolean pingIp(String ip) {
     
try { // ping -c 3 -w 100 中 ,-c 是指ping的次数 3是指ping 3次 ,-w 100 // 以秒为单位指定超时间隔,是指超时时间为12秒 ,***这和ping速度相关谨慎更改*** Process p = Runtime.getRuntime().exec("ping -c 1 -w 120 " + ip); int status = p.waitFor(); //阻塞等待
       if (status == 0) {
          
return true; } else {
          return false; } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return false; }

windows下的实现:

public static boolean pingIp(String ip) {
        try {
            // ping -c 3 -w 100 中 ,-c 是指ping的次数 3是指ping 3次 ,-w 100
            // 以秒为单位指定超时间隔,是指超时时间为12秒 ,***这和ping速度相关谨慎更改***
            Process p = Runtime.getRuntime().exec("ping -n 1 -w 120 " + ip);
            InputStream input = p.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuffer buffer = new StringBuffer();
            String line = null;
            while ((line = in.readLine()) != null) {
                buffer.append(line);
            }
            if(buf.toString().indexOf("请求超时") != -1) {
                return false;
            } else {
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }

请注意,上面两种平台下的实现,是不同的,linux下的那种实现明显要比windows下的那种实现效率高,那么为什么不都采用linux下的那种实现呢?这就是java

平台的Process.waitfor()方法的实现在windows下不能按接口定义返回状态。那么为什么windows就这样呢(我是无语了),经过测试,发现window下的ping命令有自身的bug:ping中指定的参数-w是来设置ping阻塞等待时间的,但是该参数在windows完全不起作用,这也就是在windows平台下使用Process.waitfor()不能正确返回命令执行状态的原因。哎,我只能说windows太过聪明,把真相都掩盖在他的面具下面,再次鄙视windows。

附Process.waitfor()方法的说明:

int java.lang.Process.waitFor() throws InterruptedException

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. This method returns immediately if the subprocess has already terminated. If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.

Returns:
the exit value of the subprocess represented by this Process object. By convention, the value 0 indicates normal termination.
Throws:
InterruptedException - if the current thread is interrupted by another thread while it is waiting, then the wait is ended and an InterruptedException is thrown.

 

posted @ 2015-04-28 18:17  JerryShao  阅读(2475)  评论(1编辑  收藏  举报