From def612e7b7627ea57a32d27ecd0d5e7e0bef2f13 Mon Sep 17 00:00:00 2001 From: Federico Fissore Date: Fri, 19 Jul 2013 15:17:27 +0200 Subject: [PATCH] NetworkDiscovery: InetAddress.isReachable() is unreliable, let's open a socket --- .../discoverers/NetworkDiscovery.java | 7 ++--- app/src/processing/app/helpers/NetUtils.java | 28 +++++++++++++++++++ 2 files changed, 30 insertions(+), 5 deletions(-) create mode 100644 app/src/processing/app/helpers/NetUtils.java diff --git a/app/src/cc/arduino/packages/discoverers/NetworkDiscovery.java b/app/src/cc/arduino/packages/discoverers/NetworkDiscovery.java index 925e91b65..9fa41b30f 100644 --- a/app/src/cc/arduino/packages/discoverers/NetworkDiscovery.java +++ b/app/src/cc/arduino/packages/discoverers/NetworkDiscovery.java @@ -4,13 +4,13 @@ import cc.arduino.packages.BoardPort; import cc.arduino.packages.Discovery; import cc.arduino.packages.discoverers.network.NetworkChecker; import processing.app.Base; +import processing.app.helpers.NetUtils; import processing.app.helpers.PreferencesMap; import processing.app.zeroconf.jmdns.ArduinoDNSTaskStarter; import javax.jmdns.*; import javax.jmdns.impl.DNSTaskStarter; import java.io.IOException; -import java.net.Inet4Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.*; @@ -33,14 +33,11 @@ public class NetworkDiscovery implements Discovery, ServiceListener, cc.arduino. Iterator iterator = ports.iterator(); while (iterator.hasNext()) { try { - InetAddress address = Inet4Address.getByName(iterator.next().getAddress()); - if (!address.isReachable(100)) { + if (!NetUtils.isReachable(InetAddress.getByName(iterator.next().getAddress()))) { iterator.remove(); } } catch (UnknownHostException e) { iterator.remove(); - } catch (IOException e) { - iterator.remove(); } } return ports; diff --git a/app/src/processing/app/helpers/NetUtils.java b/app/src/processing/app/helpers/NetUtils.java new file mode 100644 index 000000000..312205fce --- /dev/null +++ b/app/src/processing/app/helpers/NetUtils.java @@ -0,0 +1,28 @@ +package processing.app.helpers; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.Socket; + +public abstract class NetUtils { + + public static boolean isReachable(InetAddress address) { + Socket socket = null; + try { + socket = new Socket(); + socket.connect(new InetSocketAddress(address, 80), 100); + return true; + } catch (IOException e) { + return false; + } finally { + if (socket != null) { + try { + socket.close(); + } catch (IOException e) { + // noop + } + } + } + } +}