List of usage examples for java.net NetworkInterface isLoopback
public boolean isLoopback() throws SocketException
From source file:ws.argo.BrowserWeb.BrowserWebController.java
private Properties getPropeGeneratorProps() throws UnknownHostException { if (pgProps != null) return pgProps; InputStream in = getPropertiesFileInputStream(); pgProps = new Properties(); if (in != null) { try {/*from ww w.j av a2 s. com*/ pgProps.load(in); } catch (IOException e) { // TODO Auto-generated catch block // Should log the props file issue setDefaultProbeGeneratorProperties(pgProps); } } if (pgProps.getProperty("listenerIPAddress", "").equals("")) { // If the listenerIPAddress is blank, then try to get the ip address of the interface String hostIPAddr = null; try { NetworkInterface n = NetworkInterface .getByName(pgProps.getProperty("listenerInterfaceName", "en0")); if (!n.isLoopback()) { Enumeration ee = n.getInetAddresses(); while (ee.hasMoreElements()) { InetAddress i = (InetAddress) ee.nextElement(); hostIPAddr = i.getHostName(); System.out.println(hostIPAddr); } } } catch (SocketException e) { System.out.println("A socket exception occurred."); } if (hostIPAddr == null) { hostIPAddr = InetAddress.getLocalHost().getHostName(); System.out.println("Defaulting to local address: " + hostIPAddr); } pgProps.put("listenerIPAddress", hostIPAddr); } return pgProps; }
From source file:net.mm2d.dmsexplorer.ServerListActivity.java
private Collection<NetworkInterface> getWifiInterface() { final NetworkInfo ni = mConnectivityManager.getActiveNetworkInfo(); if (ni == null || !ni.isConnected() || ni.getType() != ConnectivityManager.TYPE_WIFI) { return null; }/* ww w. j av a 2 s . co m*/ final InetAddress address = getWifiInetAddress(); if (address == null) { return null; } final Enumeration<NetworkInterface> nis; try { nis = NetworkInterface.getNetworkInterfaces(); } catch (final SocketException e) { return null; } while (nis.hasMoreElements()) { final NetworkInterface nif = nis.nextElement(); try { if (nif.isLoopback() || nif.isPointToPoint() || nif.isVirtual() || !nif.isUp()) { continue; } final List<InterfaceAddress> ifas = nif.getInterfaceAddresses(); for (final InterfaceAddress a : ifas) { if (a.getAddress().equals(address)) { final Collection<NetworkInterface> c = new ArrayList<>(); c.add(nif); return c; } } } catch (final SocketException ignored) { } } return null; }
From source file:org.openhab.binding.network.internal.utils.NetworkUtils.java
/** * Gets every IPv4 Address on each Interface except the loopback * The Address format is ip/subnet/*from w w w . j a va 2 s . co m*/ * * @return The collected IPv4 Addresses */ public Set<String> getInterfaceIPs() { Set<String> interfaceIPs = new HashSet<>(); Enumeration<NetworkInterface> interfaces; try { interfaces = NetworkInterface.getNetworkInterfaces(); } catch (SocketException ignored) { // If we are not allowed to enumerate, we return an empty result set. return interfaceIPs; } // For each interface ... for (Enumeration<NetworkInterface> en = interfaces; en.hasMoreElements();) { NetworkInterface networkInterface = en.nextElement(); boolean isLoopback = true; try { isLoopback = networkInterface.isLoopback(); } catch (SocketException ignored) { } if (!isLoopback) { // .. and for each address ... for (Iterator<InterfaceAddress> it = networkInterface.getInterfaceAddresses().iterator(); it .hasNext();) { // ... get IP and Subnet InterfaceAddress interfaceAddress = it.next(); interfaceIPs.add(interfaceAddress.getAddress().getHostAddress() + "/" + interfaceAddress.getNetworkPrefixLength()); } } } return interfaceIPs; }
From source file:org.springframework.data.hadoop.util.net.DefaultHostInfoDiscovery.java
private List<NetworkInterface> filterInterfaces(List<NetworkInterface> interfaces) { List<NetworkInterface> filtered = new ArrayList<NetworkInterface>(); for (NetworkInterface nic : interfaces) { boolean match = false; try {//from w w w .j a va2 s. c o m match = pointToPoint && nic.isPointToPoint(); } catch (SocketException e) { } try { match = !match && loopback && nic.isLoopback(); } catch (SocketException e) { } // last, if we didn't match anything, let all pass // if matchInterface is not set, otherwise do pattern // matching if (!match && !StringUtils.hasText(matchInterface)) { match = true; } else if (StringUtils.hasText(matchInterface)) { match = nic.getName().matches(matchInterface); } if (match) { filtered.add(nic); } } return filtered; }
From source file:org.psit.transwatcher.TransWatcher.java
private String getBroadcastIP() { String myIP = null;/*from w w w .j a v a2s.c o m*/ try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements() && myIP == null) { NetworkInterface current = interfaces.nextElement(); notifyMessage(current.toString()); notifyMessage("Name: " + current.getName()); if (!current.isUp() || current.isLoopback() || current.isVirtual() || !current.getName().startsWith("wl")) continue; Enumeration<InetAddress> addresses = current.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress current_addr = addresses.nextElement(); if (current_addr.isLoopbackAddress()) continue; if (current_addr instanceof Inet4Address) { myIP = current_addr.getHostAddress(); break; } } } } catch (Exception exc) { notifyMessage("Error determining network interfaces:\n"); } if (myIP != null) { // broadcast for IPv4 StringTokenizer st = new StringTokenizer(myIP, "."); StringBuffer broadcastIP = new StringBuffer(); // hate that archaic string puzzle broadcastIP.append(st.nextElement()); broadcastIP.append("."); broadcastIP.append(st.nextElement()); broadcastIP.append("."); broadcastIP.append(st.nextElement()); broadcastIP.append("."); broadcastIP.append("255"); return broadcastIP.toString(); } return null; }
From source file:org.tellervo.desktop.wsi.WSIServerDetails.java
/** * Ping the server to update status//from w ww .j a v a2 s.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.sakuli.actions.environment.CipherUtil.java
/** * fetch the local network interfaceLog and reads out the MAC of the chosen encryption interface. * Must be called before the methods {@link #encrypt(String)} or {@link #decrypt(String)}. * * @throws SakuliCipherException for wrong interface names and MACs. */// w w w. ja v a2 s . c o m @PostConstruct public void scanNetworkInterfaces() throws SakuliCipherException { Enumeration<NetworkInterface> networkInterfaces; try { interfaceName = checkEthInterfaceName(); networkInterfaces = getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface anInterface = networkInterfaces.nextElement(); if (anInterface.getHardwareAddress() != null) { interfaceLog = interfaceLog + "\nNET-Interface " + anInterface.getIndex() + " - Name: " + anInterface.getName() + "\t MAC: " + formatMAC(anInterface.getHardwareAddress()) + "\t VirtualAdapter: " + anInterface.isVirtual() + "\t Loopback: " + anInterface.isLoopback() + "\t Desc.: " + anInterface.getDisplayName(); } if (anInterface.getName().equals(interfaceName)) { macOfEncryptionInterface = anInterface.getHardwareAddress(); } } if (macOfEncryptionInterface == null) { throw new SakuliCipherException( "Cannot resolve MAC address ... please check your config of the property: " + ActionProperties.ENCRYPTION_INTERFACE + "=" + interfaceName, interfaceLog); } } catch (Exception e) { throw new SakuliCipherException(e, interfaceLog); } }
From source file:org.eclipse.smarthome.binding.lifx.internal.LifxLightDiscovery.java
@Override protected void activate(Map<String, Object> configProperties) { super.activate(configProperties); broadcastAddresses = new ArrayList<InetSocketAddress>(); interfaceAddresses = new ArrayList<InetAddress>(); Enumeration<NetworkInterface> networkInterfaces = null; try {/*w w w.j a va2 s. com*/ networkInterfaces = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { logger.debug("An exception occurred while discovering LIFX lights : '{}'", e.getMessage()); } if (networkInterfaces != null) { while (networkInterfaces.hasMoreElements()) { NetworkInterface iface = networkInterfaces.nextElement(); try { if (iface.isUp() && !iface.isLoopback()) { for (InterfaceAddress ifaceAddr : iface.getInterfaceAddresses()) { if (ifaceAddr.getAddress() instanceof Inet4Address) { logger.debug("Adding '{}' as interface address with MTU {}", ifaceAddr.getAddress(), iface.getMTU()); if (iface.getMTU() > bufferSize) { bufferSize = iface.getMTU(); } interfaceAddresses.add(ifaceAddr.getAddress()); if (ifaceAddr.getBroadcast() != null) { logger.debug("Adding '{}' as broadcast address", ifaceAddr.getBroadcast()); broadcastAddresses .add(new InetSocketAddress(ifaceAddr.getBroadcast(), BROADCAST_PORT)); } } } } } catch (SocketException e) { logger.debug("An exception occurred while discovering LIFX lights : '{}'", e.getMessage()); } } } }
From source file:com.git.original.common.utils.IPUtils.java
/** * ?IP?/* ww w. ja va2s . c o m*/ * <p> * :<br/> * 1. 220.xxx.xxx.xxx<br> * 2. 123.xxx.xxx.xxx<br> * other<br> * * @return * @throws SocketException * If an I/O error occurs. * @throws NullPointerException * can not found the interface * @throws RuntimeException * can not get net address */ public static InetAddress getWANIpv4Address(String interfaceName) throws SocketException, NullPointerException, RuntimeException { InetAddress ipStartWith123 = null; InetAddress ipv4Addr = null; if (StringUtils.isNotEmpty(interfaceName)) { // ? NetworkInterface netInterface = NetworkInterface.getByName(interfaceName.trim()); if (netInterface == null) { throw new NullPointerException("can not found the network interface by name: " + interfaceName); } Enumeration<InetAddress> addrEnum = netInterface.getInetAddresses(); while (addrEnum.hasMoreElements()) { InetAddress addr = addrEnum.nextElement(); String hostAddr = addr.getHostAddress(); if (hostAddr.startsWith("220.")) { return addr; } else if (ipStartWith123 == null && hostAddr.startsWith("123.")) { ipStartWith123 = addr; } else if (addr instanceof Inet4Address) { ipv4Addr = addr; } } } else { /* * ??? */ Enumeration<NetworkInterface> interfaceEnum = NetworkInterface.getNetworkInterfaces(); while (interfaceEnum.hasMoreElements()) { NetworkInterface netInterface = interfaceEnum.nextElement(); if (netInterface.isLoopback() || !netInterface.isUp()) { continue; } Enumeration<InetAddress> addrEnum = netInterface.getInetAddresses(); while (addrEnum.hasMoreElements()) { InetAddress addr = addrEnum.nextElement(); String hostAddr = addr.getHostAddress(); if (hostAddr.startsWith("220.")) { return addr; } else if (ipStartWith123 == null && hostAddr.startsWith("123.")) { ipStartWith123 = addr; } else if (addr instanceof Inet4Address) { ipv4Addr = addr; } } } } if (ipStartWith123 != null) { return ipStartWith123; } else if (ipv4Addr != null) { return ipv4Addr; } throw new RuntimeException("can not get WAN Address"); }
From source file:org.apache.hadoop.hdfs.MiniAvatarCluster.java
/** * Retrieves the name of the loopback interface in a platform independent way. *//* ww w.jav a 2 s .c om*/ private static String getLoopBackInterface() throws IOException { String loopBack = "lo"; Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); while (ifaces.hasMoreElements()) { NetworkInterface iface = ifaces.nextElement(); if (iface.isLoopback()) { loopBack = iface.getName(); break; } } return loopBack; }