2

I have been trying to get the name or the ip of all computers on the network I am on in Java.

I have tried pinging for each one with 2 different ways:

Process p = java.lang.Runtime.getRuntime().exec("ping -n 1 " + host);
returnval = p.waitFor();

This returns 0 for every address even when it fails.

and

InetAddress.getByAddress(host).isReachable(timeout);

Always returning false

The computers appear in Windows network tab in explorer.

Is there some way to retrieve a list of names of those computer in Java to use?

3 Answers3

3

Windows?

net view

or

arp -a

Last one gives MAC addresses.

Xabster
  • 3,710
  • 15
  • 21
1

Extending on Xabsters answer I was able to achieve a list via the following code.

Runtime rt = Runtime.getRuntime();
    try {
        Process p = rt.exec("arp -a");

        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

        String s = null;
        while ((s = stdInput.readLine()) != null) {
            s = s.trim();
            if (!s.startsWith("I") && s.length >0)
            System.out.println(s.split(" ")[0]);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
1

Just a complement to above answers.

InetAddress.getByName(host).isReachable(timeout); which would be the java way of doing this (portable across different architectures), did not work because it expects a host name. When using IP addresses, you should use :

InetAddress.getByAddress(host).isReachable(timeout);

That is the platform independant way.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252