Skip to content

Instantly share code, notes, and snippets.

@chris-allan
Last active December 19, 2015 19:38
Show Gist options
  • Select an option

  • Save chris-allan/6007463 to your computer and use it in GitHub Desktop.

Select an option

Save chris-allan/6007463 to your computer and use it in GitHub Desktop.
Version of the NetworkChecker from OMERO.insight that has full debugging throughout
/*
* org.openmicroscopy.shoola.env.data.NetworkChecker
*
*------------------------------------------------------------------------------
* Copyright (C) 2006-2012 University of Dundee & Open Microscopy Environment.
* All rights reserved.
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*------------------------------------------------------------------------------
*/
//Java imports
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
//Third-party libraries
//Application-internal dependencies
/**
* Checks if the network is still up.
*
* @author Jean-Marie Burel     
* <a href="mailto:j.burel@dundee.ac.uk">j.burel@dundee.ac.uk</a>
* @since 4.4
*/
@SuppressWarnings("unchecked")
public class NetworkChecker {
@SuppressWarnings("rawtypes")
static private Class NetworkInterfaceClass = null;
static private Method getNetworkInterfacesMethod = null;
static private Method isUpMethod = null;
static private Method isLoopbackMethod = null;
static private boolean useReflectiveCheck = false;
static {
//
// Perform static lookup via reflection of the methods
// needed to run Java 6 network checks.
//
try {
NetworkInterfaceClass = Class.forName("java.net.NetworkInterface");
getNetworkInterfacesMethod = NetworkInterfaceClass.getMethod("getNetworkInterfaces");
isUpMethod = NetworkInterfaceClass.getMethod("isUp");
isLoopbackMethod = NetworkInterfaceClass.getMethod("isLoopback");
useReflectiveCheck = true;
} catch (ClassNotFoundException e) {
// Knowingly using System.err since 1) this will be primarily used on
// Linux in the first instance and 2) we don't have access to a logger.
System.err.println("NetworkInterface class not found: assuming Java 1.5");
} catch (SecurityException e) {
// This should not happen. Logging (at ERROR)
e.printStackTrace();
} catch (NoSuchMethodException e) {
// This should not happen. Logging (at ERROR)
e.printStackTrace();
}
}
/**
* The IP Address of the server the client is connected to
* or <code>null</code>.
*/
private InetAddress ipAddress;
/** Creates a new instance.
*/
public NetworkChecker()
{
this(null);
}
/**
* Creates a new instance.
*
* @param ipAddress The IP address of the server the client is connected to
* or <code>null</code>.
*/
public NetworkChecker(String ipAddress)
{
if (ipAddress != null) {
try {
this.ipAddress = InetAddress.getByName(ipAddress);
} catch (UnknownHostException e) {
// Ignored
}
}
}
/**
* Run the standard Java 1.6 check using reflection. If this is not 1.6 or later, then
* exit successfully, printing this assumption to System.err. If any odd reflection error
* occurs, then act as if the network is up, even though we don't know. Finally, if the
* reflection code works properly, throw an {@link UnknownHostException} if no up, non-loopback
* network is found.
*
* @throws UnknownHostException
*/
@SuppressWarnings({ "rawtypes"})
public boolean reflectiveCheck() throws UnknownHostException {
if (!useReflectiveCheck) {
return true;
}
try {
Enumeration interfaces = (Enumeration) getNetworkInterfacesMethod.invoke(null);
if (interfaces != null) {
while (interfaces.hasMoreElements()) {
Object ni = interfaces.nextElement();
Boolean isUp = (Boolean) isUpMethod.invoke(ni);
Boolean isLoopback = (Boolean) isLoopbackMethod.invoke(ni);
if (isUp != null && isLoopback != null && (isUp && !isLoopback)) {
// TODO: add logging here for the successful check.
return true;
}
}
}
} catch (Exception e) {
// This should not happen. It likely implies that something has happened in
// our reflection code, since no checked exceptions are thrown from the 1.6 code.
System.err.println("Failed during reflection. Assuming network is up.");
e.printStackTrace();
return true;
}
// If we reach here and no exception has been thrown then we assume that
// there is no network.
return false;
}
/**
* Returns <code>true</code> if the network is still up, otherwise
* throws an <code>UnknownHostException</code>.
*
* @return See above.
* @throws Exception Thrown if the network is down.
*/
public boolean isNetworkup()
throws Exception
{
boolean networkup = false;
List<String> ips = new ArrayList<String>();
if (useReflectiveCheck) {
// On Java 1.6+, reflectiveCheck will perform a proper check.
networkup = reflectiveCheck();
} else {
Enumeration<NetworkInterface> interfaces =
NetworkInterface.getNetworkInterfaces();
if (interfaces != null && !networkup) {
NetworkInterface ni;
InetAddress ia;
while (interfaces.hasMoreElements()) {
ni = interfaces.nextElement();
Enumeration<InetAddress> e = ni.getInetAddresses();
if (!ni.getDisplayName().startsWith("lo")) {
while (e.hasMoreElements()) {
ia = (InetAddress) e.nextElement();
if (!ia.isAnyLocalAddress() &&
!ia.isLoopbackAddress()) {
if (!ia.getHostName().equals(
ia.getHostAddress())) {
networkup = true;
break;
}
}
}
if (networkup) break;
}
}
}
}
if (!networkup) {
if (ipAddress != null && ipAddress.isLoopbackAddress()) {
return true;
}
throw new UnknownHostException("Network is down.");
}
return networkup;
}
public static void main(String[] args) throws Exception {
NetworkChecker nc = new NetworkChecker();
System.err.println("Java version: " + System.getProperty("java.version"));
System.err.println("isNetworkup()?: " + nc.isNetworkup());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment