Get network names of computers

I am looking for a better way to get the names of computers on a LAN with Java. I tried:

byte[] ip = {(byte)192,(byte)168,(byte)178,(byte)1}; for(int i=1;i<255;i++) { ip[3] = (byte)i; try { InetAddress addr = InetAddress.getByAddress(ip); String s = addr.getHostName(); System.out.println(s); } catch(UnknownHostException e) { System.out.println(e.getMessage()); } } 

... but it's too slow. Is there another way?

I am on Windows.

Any ideas are welcome.

+4
source share
2 answers

You can increase speed using multiple threads.

Let each thread do one or more iterations of your try block.

+8
source

For those who are wondering, here is what I came up with:

 import java.net.InetAddress; import java.net.UnknownHostException; public class nameLookup implements Runnable { byte[] ip; String[] names; int index; public nameLookup(byte[] ip,int index,String[] names) { this.ip = ip; this.names = names; this.index = index; } public void run() { try { InetAddress addr = InetAddress.getByAddress(ip); names[index]= addr.getHostName(); } catch(UnknownHostException e) { System.out.println(e.getMessage()); } } public static String[] lookUp() { byte[] ip = {(byte)192,(byte)168,(byte)178,(byte)1}; String[] names = new String[254]; Thread threads[] = new Thread[254]; for(int i=0;i<254;i++) { ip[3] = (byte)(i+1); threads[i] = new Thread(new nameLookup(ip,i,names)); threads[i].start(); } for(int i=0;i<254;i++) { try { threads[i].join(); } catch (InterruptedException e) { System.out.print(e.getMessage()); } } return names; } } 

I still want it to be faster, but now it is at least acceptable.

+2
source

Source: https://habr.com/ru/post/1494562/


All Articles