Android Debugging Inetaddress.Isreachable

Checking Host Reachability/Availability in Android

It's not pretty but this is how I did it:

boolean exists = false;

try {
SocketAddress sockaddr = new InetSocketAddress(ip, port);
// Create an unbound socket
Socket sock = new Socket();

// This method will block no more than timeoutMs.
// If the timeout occurs, SocketTimeoutException is thrown.
int timeoutMs = 2000; // 2 seconds
sock.connect(sockaddr, timeoutMs);
exists = true;
} catch(IOException e) {
// Handle exception
}

Latency time in android

For me, something like this does the trick:

Process process = Runtime.getRuntime().exec("ping -c 1 google.com");
process.waitFor();

You can regex through the answer by reading InputStream provided by process.

Kotlin: NetworkOnMainThreadException error when trying to run InetAddress.isReachable()

As the exception says you are trying to do a network call on main thread which is prohibited.

An easy way to fix this would be to make the function suspendable and switch to a background thread

private suspend fun hasConnection() {
withContext(Dispatchers.IO) {
var address: InetAddress = InetAddress.getByName("192.168.1.1")
val timeout = 1500
if (address.isReachable(timeout)){
status.text = "Available"
}else{
status.text = "Disconnected"
}
}
}

When calling hasConnection() use lifecycleScope from Activity level to launch a coroutine which will call your hasConnection()

------------- Somewhere in your Activity -------------


lifecycleScope.launch {
hasConnection()
}

isReachable() returns false in android

Well, i found that android keep MAC addreses of devices for about 10 min (On different devices - different time), and only way - use ADB shell command to clear that list, BUT! it works only on rooted devices.

But this code can help you (works not with all devices):

public void getListOfConnectedDevice() {
final Thread thread = new Thread(new Runnable() {

@Override
public void run() {
macAddresses.clear();
BufferedReader br = null;
boolean isFirstLine = true;
try {

br = new BufferedReader(new FileReader("/proc/net/arp"));
String line;

while ((line = br.readLine()) != null) {
if (isFirstLine) {
isFirstLine = false;
continue;
}

String[] splitted = line.split(" +");

if (splitted != null && splitted.length >= 4) {

String ipAddress = splitted[0];
String macAddress = splitted[3];

Node node = new Node(ipAddress, macAddress);
boolean isReachable = node.isReachable;
Log.d(TAG, "isReachable: " + isReachable);
if (isReachable) {
Log.d("Device Information", ipAddress + " : "
+ macAddress);
macAddresses.add(macAddress);
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
thread.start();
}


Related Topics



Leave a reply



Submit