I'm trying to create a function that lists all connected devices on a local network.
What I do is to ping any address from addresspace x.x.x.0 to x.x.x.255, but it doesn't seem to work properly. Could anyone explain or extend my code somehow? I do get a response from the phone (10.0.0.17) and a default gateway (10.0.0.138). The latter shouldn't even be there (matter of fact I don't know what a default gateway is but ignore that). I am missing the IP from this computer though.
public ArrayList<InetAddress> getConnectedDevices(String YourPhoneIPAddress) {
ArrayList<InetAddress> ret = new ArrayList<InetAddress>();
LoopCurrentIP = 0;
// String IPAddress = "";
String[] myIPArray = YourPhoneIPAddress.split("\.");
InetAddress currentPingAddr;
for (int i = 0; i <= 255; i++) {
try {
// build the next IP address
currentPingAddr = InetAddress.getByName(myIPArray[0] + "." +
myIPArray[1] + "." +
myIPArray[2] + "." +
Integer.toString(LoopCurrentIP));
// 50ms Timeout for the "ping"
if (currentPingAddr.isReachable(50)) {
if(currentPingAddr.getHostAddress() != YourPhoneIPAddress){
ret.add(currentPingAddr);
}
}
} catch (UnknownHostException ex) {
} catch (IOException ex) {
}
LoopCurrentIP++;
}
return ret;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…