List of usage examples for java.net InetAddress isLoopbackAddress
public boolean isLoopbackAddress()
From source file:org.springframework.data.hadoop.util.net.DefaultHostInfoDiscovery.java
private List<InetAddress> filterAddresses(List<InetAddress> addresses) { List<InetAddress> filtered = new ArrayList<InetAddress>(); for (InetAddress address : addresses) { // take only ipv4 addresses whose byte array length is always 4 boolean match = address.getAddress() != null && address.getAddress().length == 4; // check loopback if (!loopback && address.isLoopbackAddress()) { match = false;/*from w w w.java 2 s.c o m*/ } // match cidr if defined if (match && StringUtils.hasText(matchIpv4)) { match = matchIpv4(matchIpv4, address.getHostAddress()); } if (match) { filtered.add(address); } } return filtered; }
From source file:com.seleuco.mame4droid.NetPlay.java
public String getIPAddress() { try {/*from w w w. j a va2s . c o m*/ Enumeration<NetworkInterface> ifaceList; NetworkInterface selectedIface = null; // First look for a WLAN interface ifaceList = NetworkInterface.getNetworkInterfaces(); while (selectedIface == null && ifaceList.hasMoreElements()) { NetworkInterface intf = ifaceList.nextElement(); if (intf.getName().startsWith("wlan")) { List<InetAddress> addrs = Collections.list(intf.getInetAddresses()); for (InetAddress addr : addrs) { if (!addr.isLoopbackAddress()) { String sAddr = addr.getHostAddress().toUpperCase(); boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr); if (isIPv4) return sAddr; } } } } // If we didn't find that, look for an Ethernet interface ifaceList = NetworkInterface.getNetworkInterfaces(); while (selectedIface == null && ifaceList.hasMoreElements()) { NetworkInterface intf = ifaceList.nextElement(); if (intf.getName().startsWith("eth")) { List<InetAddress> addrs = Collections.list(intf.getInetAddresses()); for (InetAddress addr : addrs) { if (!addr.isLoopbackAddress()) { String sAddr = addr.getHostAddress().toUpperCase(); boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr); if (isIPv4) return sAddr; } } } } List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface intf : interfaces) { List<InetAddress> addrs = Collections.list(intf.getInetAddresses()); for (InetAddress addr : addrs) { if (!addr.isLoopbackAddress()) { String sAddr = addr.getHostAddress().toUpperCase(); boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr); if (isIPv4) return sAddr; } } } } catch (Exception ex) { } return null; }
From source file:edu.umass.cs.msocket.proxy.ProxyGnsPublisher.java
/** * Establish a connection with the GNS, register the proxy in the proxy group, * start a monitoring socket and register its IP in the GNS, * //from ww w . java2s .c om * @throws Exception */ public void registerProxyInGns() throws Exception { logger.info("Looking for proxy " + proxyName + " GUID and certificates..."); GuidEntry myGuid = KeyPairUtils.getGuidEntryFromPreferences( gnsCredentials.getGnsHost() + ":" + gnsCredentials.getGnsPort(), proxyName); final UniversalGnsClient gnsClient = gnsCredentials.getGnsClient(); if (myGuid == null) { logger.info("No keys found for proxy " + proxyName + ". Generating new GUID and keys"); myGuid = gnsClient.guidCreate(gnsCredentials.getGuidEntry(), proxyName); } logger.info("Proxy has guid " + myGuid.getGuid()); // Determine our IP String sIp = null; BufferedReader in; InetAddress addr; try { addr = ((InetSocketAddress) proxySocketAddres).getAddress(); if (addr != null && !addr.isLinkLocalAddress() && !addr.isLoopbackAddress() && !addr.isSiteLocalAddress()) sIp = addr.getHostAddress(); } catch (Exception e) { logger.log(Level.WARNING, "Failed to resolve proxy address " + proxySocketAddres, e); } if (sIp == null) { logger.warning("Local proxy address (" + proxySocketAddres + ") does not seem to be a public address"); try { logger.info("Determining local IP"); // Determine our external IP address by contacting http://icanhazip.com URL whatismyip = new URL("http://icanhazip.com"); in = new BufferedReader(new InputStreamReader(whatismyip.openStream())); sIp = in.readLine(); in.close(); } catch (Exception e) { } } ProxyInfo proxyInfo = new ProxyInfo(myGuid.getGuid(), proxyName, sIp); try { // Contact http://freegeoip.net/csv/[IP] to resolve IP address location URL locator = new URL("http://freegeoip.net/csv/" + sIp); in = new BufferedReader(new InputStreamReader(locator.openStream())); String csv = in.readLine(); in.close(); // Read location result StringTokenizer st = new StringTokenizer(csv, ","); if (!st.hasMoreTokens()) throw new IOException("Failed to read IP"); st.nextToken(); // IP if (!st.hasMoreTokens()) throw new IOException("Failed to read country code"); String countryCode = st.nextToken().replace("\"", ""); proxyInfo.setCountryCode(countryCode); if (!st.hasMoreTokens()) throw new IOException("Failed to read country name"); String countryName = st.nextToken().replace("\"", ""); proxyInfo.setCountryName(countryName); if (!st.hasMoreTokens()) throw new IOException("Failed to read state code"); String stateCode = st.nextToken().replace("\"", ""); proxyInfo.setStateCode(stateCode); if (!st.hasMoreTokens()) throw new IOException("Failed to read state name"); String stateName = st.nextToken().replace("\"", ""); proxyInfo.setStateName(stateName); if (!st.hasMoreTokens()) throw new IOException("Failed to read city"); String city = st.nextToken().replace("\"", ""); proxyInfo.setCity(city); if (!st.hasMoreTokens()) throw new IOException("Failed to read zip"); String zip = st.nextToken().replace("\"", ""); proxyInfo.setZipCode(zip); if (!st.hasMoreTokens()) throw new IOException("Failed to read latitude"); String latitudeStr = st.nextToken().replace("\"", ""); double latitude = Double.parseDouble(latitudeStr); if (!st.hasMoreTokens()) throw new IOException("Failed to read longitude"); String longitudeStr = st.nextToken().replace("\"", ""); double longitude = Double.parseDouble(longitudeStr); proxyInfo.setLatLong(new GlobalPosition(latitude, longitude, 0)); } catch (Exception e) { logger.log(Level.WARNING, "Failed to locate IP address " + e); } // Look for the group GUID String groupGuid = gnsClient.lookupGuid(proxyGroupName); // Check if we are a member of the group boolean isVerified = false; try { JSONArray members = gnsClient.groupGetMembers(groupGuid, myGuid); for (int i = 0; i < members.length(); i++) { if (myGuid.getGuid().equals(members.get(i))) { isVerified = true; break; } } } catch (Exception e) { /* * At this point we couldn't get or parse the member list probably because * we don't have read access to it. This means we are not a verified * member. */ logger.log(Level.INFO, "Could not access the proxy group member list because we are not likely a group member yet (" + e + ")"); } // Make sure we advertise ourselves as a proxy and make the field readable // by everyone gnsClient.fieldReplaceOrCreate(myGuid.getGuid(), GnsConstants.SERVICE_TYPE_FIELD, new JSONArray().put(GnsConstants.PROXY_SERVICE), myGuid); gnsClient.aclAdd(AccessType.READ_WHITELIST, myGuid, GnsConstants.SERVICE_TYPE_FIELD, null); // Publish external IP (readable by everyone) InetSocketAddress externalIP = (InetSocketAddress) proxySocketAddres; gnsClient.fieldReplaceOrCreate(myGuid.getGuid(), GnsConstants.PROXY_EXTERNAL_IP_FIELD, new JSONArray().put(externalIP.getAddress().getHostAddress() + ":" + externalIP.getPort()), myGuid); gnsClient.aclAdd(AccessType.READ_WHITELIST, myGuid, GnsConstants.PROXY_EXTERNAL_IP_FIELD, null); // Update our location if geolocation resolution worked if (proxyInfo.getLatLong() != null) gnsClient.setLocation(proxyInfo.getLatLong().getLongitude(), proxyInfo.getLatLong().getLatitude(), myGuid); if (!isVerified) { logger.log(Level.WARNING, "This proxy has not been verified yet, it will stay in the unverified list until it gets added to the proxy group"); } gnsTimer = new GnsTimerKeepalive(gnsCredentials, myGuid, 1000); gnsTimer.start(); }
From source file:org.apache.hadoop.net.TestDNS.java
/** * TestCase: get our local address and reverse look it up *//*from w ww . ja v a2 s. co m*/ @Test public void testRDNS() throws Exception { InetAddress localhost = getLocalIPAddr(); try { String s = DNS.reverseDns(localhost, null); LOG.info("Local reverse DNS hostname is " + s); } catch (NameNotFoundException | CommunicationException e) { if (!localhost.isLinkLocalAddress() || localhost.isLoopbackAddress()) { //these addresses probably won't work with rDNS anyway, unless someone //has unusual entries in their DNS server mapping 1.0.0.127 to localhost LOG.info("Reverse DNS failing as due to incomplete networking", e); LOG.info("Address is " + localhost + " Loopback=" + localhost.isLoopbackAddress() + " Linklocal=" + localhost.isLinkLocalAddress()); } } }
From source file:org.opendaylight.ovsdb.openstack.netvirt.impl.BridgeConfigurationManagerImpl.java
private String getControllerTarget() { /* TODO SB_MIGRATION * hardcoding value, need to find better way to get local ip *///from w w w.ja v a 2 s. c o m //String target = "tcp:" + getControllerIPAddress() + ":" + getControllerOFPort(); //TODO: dirty fix, need to remove it once we have proper solution String ipaddress = null; try { for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) { NetworkInterface iface = (NetworkInterface) ifaces.nextElement(); for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) { InetAddress inetAddr = (InetAddress) inetAddrs.nextElement(); if (!inetAddr.isLoopbackAddress()) { if (inetAddr.isSiteLocalAddress()) { ipaddress = inetAddr.getHostAddress(); break; } } } } } catch (Exception e) { LOGGER.warn("ROYALLY SCREWED : Exception while fetching local host ip address ", e); } return "tcp:" + ipaddress + ":6633"; }
From source file:info.pancancer.arch3.worker.WorkerRunnable.java
/** * Get the IP address of this machine, preference is given to returning an IPv4 address, if there is one. * * @return An InetAddress object.// w w w . j av a2 s . com * @throws SocketException */ public InetAddress getFirstNonLoopbackAddress() throws SocketException { final String dockerInterfaceName = "docker"; for (NetworkInterface i : Collections.list(NetworkInterface.getNetworkInterfaces())) { if (i.getName().contains(dockerInterfaceName)) { // the virtual ip address for the docker mount is useless but is not a loopback address continue; } log.info("Examining " + i.getName()); for (InetAddress addr : Collections.list(i.getInetAddresses())) { if (!addr.isLoopbackAddress()) { // Prefer IP v4 if (addr instanceof Inet4Address) { return addr; } } } } Log.info("Could not find an ipv4 address"); for (NetworkInterface i : Collections.list(NetworkInterface.getNetworkInterfaces())) { log.info("Examining " + i.getName()); if (i.getName().contains(dockerInterfaceName)) { // the virtual ip address for the docker mount is useless but is not a loopback address continue; } // If we got here it means we never found an IP v4 address, so we'll have to return the IPv6 address. for (InetAddress addr : Collections.list(i.getInetAddresses())) { // InetAddress addr = (InetAddress) en2.nextElement(); if (!addr.isLoopbackAddress()) { return addr; } } } return null; }
From source file:de.yaacc.upnp.server.contentdirectory.YaaccContentDirectory.java
/** * get the ip address of the device//from w w w .jav a 2s . c o m * * @return the address or null if anything went wrong * */ public String getIpAddress() { String hostAddress = null; try { for (Enumeration<NetworkInterface> networkInterfaces = NetworkInterface .getNetworkInterfaces(); networkInterfaces.hasMoreElements();) { NetworkInterface networkInterface = networkInterfaces.nextElement(); for (Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses(); inetAddresses .hasMoreElements();) { InetAddress inetAddress = inetAddresses.nextElement(); if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) { hostAddress = inetAddress.getHostAddress(); } } } } catch (SocketException se) { Log.d(YaaccUpnpServerService.class.getName(), "Error while retrieving network interfaces", se); } // maybe wifi is off we have to use the loopback device hostAddress = hostAddress == null ? "0.0.0.0" : hostAddress; return hostAddress; }
From source file:com.cloud.storage.template.HttpTemplateDownloader.java
private Pair<String, Integer> validateUrl(String url) throws IllegalArgumentException { try {// w w w. j a v a 2 s . c om URI uri = new URI(url); if (!uri.getScheme().equalsIgnoreCase("http") && !uri.getScheme().equalsIgnoreCase("https")) { throw new IllegalArgumentException("Unsupported scheme for url"); } int port = uri.getPort(); if (!(port == 80 || port == 443 || port == -1)) { throw new IllegalArgumentException("Only ports 80 and 443 are allowed"); } if (port == -1 && uri.getScheme().equalsIgnoreCase("https")) { port = 443; } else if (port == -1 && uri.getScheme().equalsIgnoreCase("http")) { port = 80; } String host = uri.getHost(); try { InetAddress hostAddr = InetAddress.getByName(host); if (hostAddr.isAnyLocalAddress() || hostAddr.isLinkLocalAddress() || hostAddr.isLoopbackAddress() || hostAddr.isMulticastAddress()) { throw new IllegalArgumentException("Illegal host specified in url"); } if (hostAddr instanceof Inet6Address) { throw new IllegalArgumentException( "IPV6 addresses not supported (" + hostAddr.getHostAddress() + ")"); } return new Pair<String, Integer>(host, port); } catch (UnknownHostException uhe) { throw new IllegalArgumentException("Unable to resolve " + host); } } catch (IllegalArgumentException iae) { s_logger.warn("Failed uri validation check: " + iae.getMessage()); throw iae; } catch (URISyntaxException use) { s_logger.warn("Failed uri syntax check: " + use.getMessage()); throw new IllegalArgumentException(use.getMessage()); } }
From source file:org.alfresco.filesys.auth.PassthruServerFactory.java
public void afterPropertiesSet() throws InvalidConfigurationException { // Check if the offline check interval has been specified if (this.offlineCheckInterval != null) { // Range check the value if (this.offlineCheckInterval < MinCheckInterval || this.offlineCheckInterval > MaxCheckInterval) throw new InvalidConfigurationException("Invalid offline check interval, valid range is " + MinCheckInterval + " to " + MaxCheckInterval); // Set the offline check interval for offline passthru servers passthruServers = new PassthruServers(this.offlineCheckInterval); // DEBUG/*from w w w . j ava 2s .c o m*/ if (logger.isDebugEnabled()) logger.debug("Using offline check interval of " + this.offlineCheckInterval + " seconds"); } else { // Create the passthru server list with the default offline check interval passthruServers = new PassthruServers(); } // Propagate the debug setting if (logger.isDebugEnabled()) passthruServers.setDebug(true); // Check if the session timeout has been specified if (this.timeout != null) { // Range check the timeout if (this.timeout < MinSessionTmo || this.timeout > MaxSessionTmo) throw new InvalidConfigurationException( "Invalid session timeout, valid range is " + MinSessionTmo + " to " + MaxSessionTmo); // Set the session timeout for connecting to an authentication server passthruServers.setConnectionTimeout(this.timeout); } passthruServers.setNullDomainUseAnyServer(this.nullDomainUseAnyServer); // Check if a server name has been specified String srvList = null; if (localServer) { try { // Get the list of local network addresses InetAddress[] localAddrs = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName()); // Build the list of local addresses if (localAddrs != null && localAddrs.length > 0) { StringBuilder addrStr = new StringBuilder(); for (InetAddress curAddr : localAddrs) { if (curAddr.isLoopbackAddress() == false) { addrStr.append(curAddr.getHostAddress()); addrStr.append(","); } } if (addrStr.length() > 0) addrStr.setLength(addrStr.length() - 1); // Set the server list using the local address list srvList = addrStr.toString(); } else throw new AlfrescoRuntimeException("No local server address(es)"); } catch (UnknownHostException ex) { throw new AlfrescoRuntimeException("Failed to get local address list"); } } if (this.server != null && this.server.length() > 0) { // Check if the server name was already set if (srvList != null) throw new AlfrescoRuntimeException("Set passthru server via local server or specify name"); // Get the passthru authenticator server name srvList = this.server; } // If the passthru server name has been set initialize the passthru connection if (srvList != null) { // Initialize using a list of server names/addresses passthruServers.setServerList(srvList); } else { // Get the domain/workgroup name String domainName = null; // Check if a domain name has been specified if (this.domain != null && this.domain.length() > 0) { // Check if the authentication server has already been set, ie. server name was also specified if (srvList != null) throw new AlfrescoRuntimeException("Specify server or domain name for passthru authentication"); domainName = this.domain; } // If the domain name has been set initialize the passthru connection if (domainName != null) { try { // Initialize using the domain passthruServers.setDomain(domainName); } catch (IOException ex) { throw new AlfrescoRuntimeException("Error setting passthru domain, " + ex.getMessage()); } } } // Check if we have an authentication server if (passthruServers.getTotalServerCount() == 0) throw new AlfrescoRuntimeException("No valid authentication servers found for passthru"); }