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)
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With