Find all IP addresses in local network

前端 未结 1 2040
陌清茗
陌清茗 2021-02-15 01:46

I want to find all IP addresses of devices in the local network I\'m currently connected to using Java code. The useful utility Advanced IP Scanner is able to find various IP ad

1条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-15 02:06

    Try to increase the timeout. I used about 5000ms, this helped me. In case you don't want to wait 5000ms * 254 = 21 minutes, try also this code with parallel pinging to the addresses:

    public static void getNetworkIPs() {
        final byte[] ip;
        try {
            ip = InetAddress.getLocalHost().getAddress();
        } catch (Exception e) {
            return;     // exit method, otherwise "ip might not have been initialized"
        }
    
        for(int i=1;i<=254;i++) {
            final int j = i;  // i as non-final variable cannot be referenced from inner class
            new Thread(new Runnable() {   // new thread for parallel execution
                public void run() {
                    try {
                        ip[3] = (byte)j;
                        InetAddress address = InetAddress.getByAddress(ip);
                        String output = address.toString().substring(1);
                        if (address.isReachable(5000)) {
                            System.out.println(output + " is on the network");
                        } else {
                            System.out.println("Not Reachable: "+output);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();     // dont forget to start the thread
        }
    }
    

    Worked perfectly for me.

    0 讨论(0)
提交回复
热议问题