I'm looking for a slicker way to access all of the online devices on a network using Java. I've currently got a method which displays all device names which have an open ServerSocket of a given port. The main application, shown below, then goes through all the devices on the subnet, and checks for this open SS. If it connects, it adds to the list of available devices.
java Code:
public class Hosts
{ public static void main
(String[] args
){ //extract subnet from local IP String[] localIP
= null; try { localIP
= InetAddress.
getLocalHost().
getHostAddress().
split("\\."); } catch (UnknownHostException e
) {} String subnet
= ""; for (int i
= 0; i
< 3; i
++) subnet
+= localIP
[i
] + "."; //display all available hosts with given port open InetAddress[] available
= getNetworkAddresses
(subnet
); for (InetAddress addr
: available
) System.
out.
println(addr.
getHostName().
split("\\.")[0]); } public static InetAddress[] getNetworkAddresses
(String subnet
){ final int PORT
= 7777; final int TIMEOUT
= 20; ArrayList
<InetAddress
> result
= new ArrayList
<InetAddress
>(); //loops through all IPs on the subnet, searching for connecting socket for (int i
= 1; i
< 255; i
++){ try { InetAddress host
= InetAddress.
getByName(subnet
+ i
); Socket s
= new Socket(); s.
connect(new InetSocketAddress
(host, PORT
), TIMEOUT
); s.
close(); //successful connect if exception not thrown result.
add(host
); } catch (SocketTimeoutException e
){ //if connection, next iteration continue; } catch (Exception e
){ e.
printStackTrace(); System.
exit(1); } } return result.
toArray(new InetAddress[result.
size()]); }}
The issue with this is that a) it requires each device to be listening (this isn't necessarily a bad thing) and b) the timeout on each socket call causes the system to take a while (I know I could use threads, but this isn't particularly slick).
Is there a more effective way to view all available devices? I've try pinging each address but this is both slow, and doesn't actually yield results