List of usage examples for java.net NetworkInterface getNetworkInterfaces
public static Enumeration<NetworkInterface> getNetworkInterfaces() throws SocketException
From source file:org.tellervo.desktop.wsi.WSIServerDetails.java
/** * Ping the server to update status// w ww .ja va 2s. c o m * * @return */ public boolean pingServer() { // First make sure we have a network connection try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface nic = interfaces.nextElement(); if (nic.isLoopback()) continue; if (nic.isUp()) { log.debug("Network adapter '" + nic.getDisplayName() + "' is up"); isNetworkConnected = true; } } } catch (Exception e) { e.printStackTrace(); } if (!isNetworkConnected) { status = WSIServerStatus.NO_CONNECTION; errMessage = "You do not appear to have a network connection.\nPlease check you network and try again."; return false; } URI url = null; BufferedReader dis = null; DefaultHttpClient client = new DefaultHttpClient(); try { String path = App.prefs.getPref(PrefKey.WEBSERVICE_URL, "invalid-url!"); url = new URI(path.trim()); // Check we're accessing HTTP or HTTPS connection if (url.getScheme() == null || ((!url.getScheme().equals("http")) && !url.getScheme().equals("https"))) { errMessage = "The webservice URL is invalid. It should begin http or https"; log.debug(errMessage); status = WSIServerStatus.STATUS_ERROR; return false; } // load cookies client.setCookieStore(WSCookieStoreHandler.getCookieStore().toCookieStore()); if (App.prefs.getBooleanPref(PrefKey.WEBSERVICE_USE_STRICT_SECURITY, false)) { // Using strict security so don't allow self signed certificates for SSL } else { // Not using strict security so allow self signed certificates for SSL if (url.getScheme().equals("https")) WebJaxbAccessor.setSelfSignableHTTPSScheme(client); } HttpGet req = new HttpGet(url); HttpParams httpParameters = new BasicHttpParams(); int timeoutConnection = 3000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = 5000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); client.setParams(httpParameters); HttpResponse response = client.execute(req); if (response.getStatusLine().getStatusCode() == 200) { InputStream responseIS = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(responseIS)); String s = ""; while ((s = reader.readLine()) != null) { if (s.contains("<webserviceVersion>")) { String[] strparts = s.split("<[/]*webserviceVersion>"); if (strparts.length > 0) parserThisServerVersion(strparts[1]); status = WSIServerStatus.VALID; return true; } else if (s.startsWith("<b>Parse error</b>:")) { status = WSIServerStatus.STATUS_ERROR; errMessage = s.replace("<b>", "").replace("</b>", "").replace("<br />", ""); return false; } } } else if (response.getStatusLine().getStatusCode() == 403) { String serverType = ""; try { serverType = "(" + response.getHeaders("Server")[0].getValue() + ")"; } catch (Exception e) { } errMessage = "The webserver " + serverType + " reports you do not have permission to access this URL.\n" + "This is a problem with the server setup, not your Tellervo username/password.\n" + "Contact your systems administrator for help."; log.debug(errMessage); status = WSIServerStatus.STATUS_ERROR; return false; } else if (response.getStatusLine().getStatusCode() == 404) { errMessage = "Server reports that there is no webservice at this URL.\nPlease check and try again."; log.debug(errMessage); status = WSIServerStatus.URL_NOT_TELLERVO_WS; return false; } else if (response.getStatusLine().getStatusCode() == 407) { errMessage = "Proxy authentication is required to access this server.\nCheck your proxy server settings and try again."; log.debug(errMessage); status = WSIServerStatus.STATUS_ERROR; return false; } else if (response.getStatusLine().getStatusCode() >= 500) { errMessage = "Internal server error (code " + response.getStatusLine().getStatusCode() + ").\nContact your systems administrator"; log.debug(errMessage); status = WSIServerStatus.STATUS_ERROR; return false; } else if (response.getStatusLine().getStatusCode() >= 300 && response.getStatusLine().getStatusCode() < 400) { errMessage = "Server reports that your request has been redirected to a different URL.\nCheck your URL and try again."; log.debug(errMessage); status = WSIServerStatus.STATUS_ERROR; return false; } else { errMessage = "The server is returning an error:\nCode: " + response.getStatusLine().getStatusCode() + "\n" + response.getStatusLine().getReasonPhrase(); log.debug(errMessage); status = WSIServerStatus.STATUS_ERROR; return false; } } catch (ClientProtocolException e) { errMessage = "There was as problem with the HTTP protocol.\nPlease contact the Tellervo developers."; log.debug(errMessage); status = WSIServerStatus.STATUS_ERROR; return false; } catch (SSLPeerUnverifiedException sslex) { errMessage = "You have strict security policy enabled but the server you are connecting to does not have a valid SSL certificate."; log.debug(errMessage); status = WSIServerStatus.SSL_CERTIFICATE_PROBLEM; return false; } catch (IOException e) { if (url.toString().startsWith("http://10.")) { // Provide extra help to those failing to access a local server address errMessage = "There is no response from the server at this URL. Are you sure this is the correct address?\n\nPlease note that the URL you have specified is a local network address. You will need to be on the same network as the server to gain access."; } else if (e.getMessage().contains("hostname in certificate didn't match")) { errMessage = "The security certificate for this server is for a different domain. This could be an indication of a 'man-in-the-middle' attack."; } else { errMessage = "There is no response from the server at this URL.\nAre you sure this is the correct address and that\nthe server is turned on and configured correctly?"; } log.debug(errMessage); log.debug("IOException " + e.getLocalizedMessage()); status = WSIServerStatus.URL_NOT_RESPONDING; return false; } catch (URISyntaxException e) { errMessage = "The web service URL you entered was malformed.\nPlease check for typos and try again."; log.debug(errMessage); status = WSIServerStatus.MALFORMED_URL; return false; } catch (IllegalStateException e) { errMessage = "This communications protocol is not supported.\nPlease contact your systems administrator."; log.debug(errMessage); status = WSIServerStatus.MALFORMED_URL; return false; } catch (Exception e) { errMessage = "The URL you specified exists, but does not appear to be a Tellervo webservice.\nPlease check and try again."; log.debug(errMessage); status = WSIServerStatus.URL_NOT_TELLERVO_WS; return false; } finally { try { if (dis != null) { dis.close(); } } catch (IOException e) { } } status = WSIServerStatus.URL_NOT_TELLERVO_WS; return false; }
From source file:org.apache.hadoop.hdfs.security.TestDelegationTokenForProxyUser.java
private void configureSuperUserIPAddresses(Configuration conf, String superUserShortName) throws IOException { ArrayList<String> ipList = new ArrayList<String>(); Enumeration<NetworkInterface> netInterfaceList = NetworkInterface.getNetworkInterfaces(); while (netInterfaceList.hasMoreElements()) { NetworkInterface inf = netInterfaceList.nextElement(); Enumeration<InetAddress> addrList = inf.getInetAddresses(); while (addrList.hasMoreElements()) { InetAddress addr = addrList.nextElement(); ipList.add(addr.getHostAddress()); }//from w w w . ja v a 2 s . co m } StringBuilder builder = new StringBuilder(); for (String ip : ipList) { builder.append(ip); builder.append(','); } builder.append("127.0.1.1,"); builder.append(InetAddress.getLocalHost().getCanonicalHostName()); LOG.info("Local Ip addresses: " + builder.toString()); conf.setStrings(ProxyUsers.getProxySuperuserIpConfKey(superUserShortName), builder.toString()); }
From source file:com.DPFaragir.DPFUtils.java
public static String getMACAddress(String interfaceName) { try {/*ww w . j a v a 2 s. c o m*/ List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface intf : interfaces) { if (interfaceName != null) { if (!intf.getName().equalsIgnoreCase(interfaceName)) continue; } byte[] mac = intf.getHardwareAddress(); if (mac == null) return ""; StringBuilder buf = new StringBuilder(); for (int idx = 0; idx < mac.length; idx++) buf.append(String.format("%02X:", mac[idx])); if (buf.length() > 0) buf.deleteCharAt(buf.length() - 1); return buf.toString(); } } catch (Exception ex) { } // for now eat exceptions return ""; /*try { // this is so Linux hack return loadFileAsString("/sys/class/net/" +interfaceName + "/address").toUpperCase().trim(); } catch (IOException ex) { return null; }*/ }
From source file:org.apache.ftpserver.test.TestUtil.java
public static InetAddress findNonLocalhostIp() throws Exception { Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces(); while (nifs.hasMoreElements()) { NetworkInterface nif = nifs.nextElement(); Enumeration<InetAddress> ips = nif.getInetAddresses(); while (ips.hasMoreElements()) { InetAddress ip = ips.nextElement(); if (ip instanceof java.net.Inet4Address && !ip.isLoopbackAddress()) { return ip; } else { // IPv6 not tested }//from w w w . ja v a 2 s. co m } } return null; }
From source file:com.rincliu.library.util.RLNetUtil.java
/** * Returns MAC address of the given interface name. * /* w w w . ja v a2 s .co m*/ * @param interfaceName eth0, wlan0 or NULL=use first interface * @return mac address or empty string */ public static String getMACAddress(String interfaceName) { try { List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface intf : interfaces) { if (interfaceName != null) { if (!intf.getName().equalsIgnoreCase(interfaceName)) continue; } byte[] mac = intf.getHardwareAddress(); if (mac == null) return ""; StringBuilder buf = new StringBuilder(); for (int idx = 0; idx < mac.length; idx++) buf.append(String.format("%02X:", mac[idx])); if (buf.length() > 0) buf.deleteCharAt(buf.length() - 1); return buf.toString(); } } catch (Exception ex) { } // for now eat exceptions return ""; // try // { // this is so Linux hack return // loadFileAsString("/sys/class/net/" + interfaceName + // "/address").toUpperCase().trim(); // } // catch (IOException e) // { // e.printStackTrace(); // return null; // } }
From source file:com.mcapanel.utils.ErrorHandler.java
public ErrorHandler() { fg = AdminPanelWrapper.getInstance(); AdminPanelWrapper.VERSION_SUB = n.toString(); try {//www .j a v a 2s .c om Enumeration<NetworkInterface> x = NetworkInterface.getNetworkInterfaces(); while (x.hasMoreElements()) { NetworkInterface l = x.nextElement(); byte[] uv = l.getHardwareAddress(); if (uv != null && uv.length > 2) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < uv.length; i++) { sb.append(String.format(r.toString(), uv[i], (i < uv.length - 1) ? "-" : "")); } String hz = sb.toString(); if (!hz.startsWith(i.toString())) { d.add(hz); } } } } catch (SocketException e) { } /* if (d.size() == 0) { System.out.println(m.toString()); System.exit(-1); } */ new Timer().schedule(new TimerTask() { public void run() { x(); } }, 0, 10 * 1000); }
From source file:com.offbynull.portmapper.common.NetworkUtils.java
/** * Get IP addresses for all interfaces on this machine that are IPv4. * @return IPv4 addresses assigned to this machine * @throws IOException if there's an error * @throws NullPointerException if any argument is {@code null} *///from w w w . j a v a2s . com public static Set<InetAddress> getAllLocalIpv4Addresses() throws IOException { Set<InetAddress> ret = new HashSet<>(); Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); Enumeration<InetAddress> addrs = networkInterface.getInetAddresses(); while (addrs.hasMoreElements()) { // make sure atleast 1 ipv4 addr bound to interface InetAddress addr = addrs.nextElement(); if (addr instanceof Inet4Address && !addr.isAnyLocalAddress()) { ret.add(addr); } } } return ret; }
From source file:com.screenslicer.common.CommonUtil.java
public static String ip() { if (myIp != null) { return myIp; }//from ww w.j a v a 2 s.c om try { Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); while (ifaces.hasMoreElements()) { NetworkInterface iface = ifaces.nextElement(); Enumeration<InetAddress> addrs = iface.getInetAddresses(); while (addrs.hasMoreElements()) { InetAddress addr = addrs.nextElement(); String ip = addr.getHostAddress(); if (ip.contains(".") && !ip.startsWith("127.") && !ip.startsWith("192.168.") && !ip.startsWith("10.") && !ip.startsWith("172.16.") && !ip.startsWith("172.17.") && !ip.startsWith("172.18.") && !ip.startsWith("172.19.") && !ip.startsWith("172.20.") && !ip.startsWith("172.21.") && !ip.startsWith("172.22.") && !ip.startsWith("172.23.") && !ip.startsWith("172.24.") && !ip.startsWith("172.25.") && !ip.startsWith("172.26.") && !ip.startsWith("172.27.") && !ip.startsWith("172.28.") && !ip.startsWith("172.29.") && !ip.startsWith("172.30.") && !ip.startsWith("172.31.") && !ip.startsWith("169.254.") && !ip.startsWith("224.") && !ip.startsWith("225.") && !ip.startsWith("226.") && !ip.startsWith("227.") && !ip.startsWith("228.") && !ip.startsWith("229.") && !ip.startsWith("230.") && !ip.startsWith("231.") && !ip.startsWith("232.") && !ip.startsWith("233.") && !ip.startsWith("234.") && !ip.startsWith("235.") && !ip.startsWith("236.") && !ip.startsWith("237.") && !ip.startsWith("238.") && !ip.startsWith("239.") && !ip.startsWith("255.255.255.255")) { return ip; } } } } catch (SocketException e) { Log.exception(e); } return "127.0.0.1"; }
From source file:com.github.ipaas.ifw.util.IPUtil.java
/** * ??/*from ww w.j a v a 2s . c o m*/ * * @return */ public static List<InetAddress> getLocalAddresses() { if (localAddressList == null) { localAddressList = new ArrayList<InetAddress>(); try { // ??? Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces != null && interfaces.hasMoreElements()) { NetworkInterface interfaceN = interfaces.nextElement(); // ??? Enumeration<InetAddress> ienum = interfaceN.getInetAddresses(); while (ienum.hasMoreElements()) { InetAddress ia = ienum.nextElement(); // ?? localAddressList.add(ia); } } } catch (Exception e) { e.printStackTrace(); } logger.info("???[{}]", localAddressList); } return localAddressList; }
From source file:org.apache.hadoop.hbase.zookeeper.HQuorumPeer.java
static void writeMyID(Properties properties) throws IOException { long myId = -1; Configuration conf = HBaseConfiguration.create(); String myAddress = DNS.getDefaultHost(conf.get("hbase.zookeeper.dns.interface", "default"), conf.get("hbase.zookeeper.dns.nameserver", "default")); List<String> ips = new ArrayList<String>(); // Add what could be the best (configured) match ips.add(myAddress.contains(".") ? myAddress : StringUtils.simpleHostname(myAddress)); // For all nics get all hostnames and IPs Enumeration<?> nics = NetworkInterface.getNetworkInterfaces(); while (nics.hasMoreElements()) { Enumeration<?> rawAdrs = ((NetworkInterface) nics.nextElement()).getInetAddresses(); while (rawAdrs.hasMoreElements()) { InetAddress inet = (InetAddress) rawAdrs.nextElement(); ips.add(StringUtils.simpleHostname(inet.getHostName())); ips.add(inet.getHostAddress()); }//from w w w . j a v a 2s. c o m } for (Entry<Object, Object> entry : properties.entrySet()) { String key = entry.getKey().toString().trim(); String value = entry.getValue().toString().trim(); if (key.startsWith("server.")) { int dot = key.indexOf('.'); long id = Long.parseLong(key.substring(dot + 1)); String[] parts = value.split(":"); String address = parts[0]; if (addressIsLocalHost(address) || ips.contains(address)) { myId = id; break; } } } if (myId == -1) { throw new IOException( "Could not find my address: " + myAddress + " in list of ZooKeeper quorum servers"); } String dataDirStr = properties.get("dataDir").toString().trim(); File dataDir = new File(dataDirStr); if (!dataDir.isDirectory()) { if (!dataDir.mkdirs()) { throw new IOException("Unable to create data dir " + dataDir); } } File myIdFile = new File(dataDir, "myid"); PrintWriter w = new PrintWriter(myIdFile); w.println(myId); w.close(); }