I am creating a basic little game and I want it to be able to scan over a LAN using Sockets, My current code works, however it's crude and slow.
My current code works as such, it gets the current computers first 2 octaves (e.g 192.168), then it does a dual for loop (0- 255) to scan from 192.168.0.0 to 192.168.255.255, In my opinion this is a very inefficient method of scanning through all of the IP's in a LAN.
This is the code:
new Thread(new Runnable() {
@Override
public void run() {
int next = 0;
try{
String ipAd = InetAddress.getLocalHost().getHostAddress();
String ipStart = ipAd.substring(0, NetHandler.nthOccurrence(ipAd, '.', 2)-1);
Socket s;
for(int i = 0 ; i < 255; i++){
for(int j = 0 ; j < 255; j++){
s = new Socket();
String ip = ipStart + (i + "." + j);
tests++;
server = ip;
try{
s.connect(new InetSocketAddress(ip, 26655), 10);
}catch(Exception e){
continue;
}
servers[next++] = ip;
componentList.add(new GuiButton(ids++, GuiMultiplayer.this, SpaceGame.WIDTH/2, SpaceGame.HEIGHT/4 - 60 + (50 * ids), ip));
}
}
}catch(Exception e){
}
}
}).start();
}
Is there an easier method to maybe list all of the devices on my LAN network? Or is my crude, slow solution the only way?
A preview of this monstrosity: