there is no straight way in android where you could do this unless if you have root access, however you could do it the classic way, for example we are sure that the range of the second part range will be always between 0-255 so first thing we need to do is, getting our IP
by using this method:
public static String getMyIPAddress() {//P.S there might be better way to get your IP address (NetworkInfo) could do it.
String myIP = null;
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
for (InetAddress addr : addrs) {
if (!addr.isLoopbackAddress()) {
String sAddr = addr.getHostAddress().toUpperCase();
boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
if (isIPv4)
myIP = sAddr;
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return myIP;
}
method above will return the current IP
that assigned to our phone, from this we could start doing PING
to indicates others who are connected to the same network, if the PING
ever returned response then definitely the IP exists in the same network follow code below in a background thread:
String ipAddress = getMyIPAddress();
String subnet = ipAddress.substring(0, ipAddress.lastIndexOf("."));
String currentHost;
for (int i = 0; i < 255; i++) {
currentHost = subnet + "." + i;
Process p1 = Runtime.getRuntime().exec("ping -c 1 " + currentHost);
int returnVal = p1.waitFor();
boolean reachable = (returnVal == 0);
if (reachable) {
//currentHost (the IP Address) actually exists in the network
}
}
as you can see in above code, we are looping through between 0-255 and Pining
each IP Address
whoever falls into reachable
is actually within the network
.