Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending DatagramPacket with no internet connection - Android

Tags:

java

android

udp

I'm using the following code to send DatagramPacket to a given address:

InetAddress address = InetAddress.getByName(anIPAddress);

DatagramSocket socket = new DatagramSocket();
DatagramPacket packet = new DatagramPacket(packetBytes, packetBytes.length,
    address, port);

socket.send(packet);
socket.close();

It works fine, but how come this code does not throw any Exception when there's no internet connection available?

I turn off both Wi-Fi and mobile data, and this code still gets executed without any errors.

Is there a way to ensure that the packet is actually sent?

(i don't care if it's reached the destination or not, i'd just like to make sure it is sent)

like image 549
justanoob Avatar asked Sep 20 '16 12:09

justanoob


1 Answers

You can use NetworkInterface.getNetworkInterfaces(); to check what interfaces are available. Then you can check with ni.isUp().

Enumeration<NetworkInterface> nets=NetworkInterface.getNetworkInterfaces();
for(int i=0; nets.hasMoreElements(); ++i) {
    NetworkInterface ni=nets.nextElement();
    if (ni.isUp() && !ni.getName().equals("lo")) {
        //ni is not local
        break;
    }
}
like image 106
krzydyn Avatar answered Sep 27 '22 21:09

krzydyn