List of usage examples for java.net InetAddress isLinkLocalAddress
public boolean isLinkLocalAddress()
From source file:org.sonar.server.platform.ServerIdGenerator.java
boolean isFixed(InetAddress address) { // Loopback addresses are in the range 127/8. // Link local addresses are in the range 169.254/16 (IPv4) or fe80::/10 (IPv6). They are "autoconfiguration" addresses. // They can assigned pseudorandomly, so they don't guarantee to be the same between two server startups. return acceptPrivateAddress || (!address.isLoopbackAddress() && !address.isLinkLocalAddress()); }
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 . j a v a 2s.co m * @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 *//* ww w . j a v a 2 s. c om*/ @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:com.cloud.storage.template.HttpTemplateDownloader.java
private Pair<String, Integer> validateUrl(String url) throws IllegalArgumentException { try {/*from w w w .j av a 2 s . c o m*/ 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:de.sjka.logstash.osgi.internal.LogstashSender.java
@SuppressWarnings("unchecked") private void addIps(JSONObject values) { List<String> ip4s = new ArrayList<>(); List<String> ip6s = new ArrayList<>(); String ip = "unknown"; try {//from w w w . j a v a 2 s. c om Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface networkInterface = networkInterfaces.nextElement(); Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses(); while (inetAddresses.hasMoreElements()) { InetAddress address = inetAddresses.nextElement(); if (address instanceof Inet4Address) { ip4s.add(address.getHostAddress() + "_" + address.getHostName()); if (!address.isLinkLocalAddress() && !address.isAnyLocalAddress() && !address.isLoopbackAddress()) { ip = address.getHostAddress(); } } if (address instanceof Inet6Address) { ip6s.add(address.getHostAddress() + "_" + address.getHostName()); } } } ip4s.add("LOC_" + InetAddress.getLocalHost().getHostAddress() + "_" + InetAddress.getLocalHost().getHostName()); if (!ip4s.isEmpty()) { values.put("ip", ip); values.put("ip4s", ip4s); } if (!ip6s.isEmpty()) { values.put("ip6s", ip6s); } } catch (UnknownHostException | SocketException e) { values.put("ip", "offline_" + e.getMessage()); } }
From source file:com.cloud.utils.net.NetUtils.java
public static String[] getNetworkParams(final NetworkInterface nic) { final List<InterfaceAddress> addrs = nic.getInterfaceAddresses(); if (addrs == null || addrs.size() == 0) { return null; }/*w w w . j a v a 2 s. co m*/ InterfaceAddress addr = null; for (final InterfaceAddress iaddr : addrs) { final InetAddress inet = iaddr.getAddress(); if (!inet.isLinkLocalAddress() && !inet.isLoopbackAddress() && !inet.isMulticastAddress() && inet.getAddress().length == 4) { addr = iaddr; break; } } if (addr == null) { return null; } final String[] result = new String[3]; result[0] = addr.getAddress().getHostAddress(); try { final byte[] mac = nic.getHardwareAddress(); result[1] = byte2Mac(mac); } catch (final SocketException e) { s_logger.debug("Caught exception when trying to get the mac address ", e); } result[2] = prefix2Netmask(addr.getNetworkPrefixLength()); return result; }
From source file:org.commonjava.maven.galley.cache.infinispan.FastLocalCacheProvider.java
private String getCurrentNodeIp() throws SocketException { final Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces(); Inet4Address top = null;/*from w ww . ja v a2 s . com*/ while (nis.hasMoreElements()) { final NetworkInterface ni = nis.nextElement(); final Enumeration<InetAddress> ips = ni.getInetAddresses(); while (ips.hasMoreElements()) { final InetAddress ip = ips.nextElement(); if (ip instanceof Inet4Address && !ip.isLinkLocalAddress()) { if (top == null) { top = (Inet4Address) ip; } else if (!top.isSiteLocalAddress() && ip.isSiteLocalAddress()) { top = (Inet4Address) ip; } } } } if (top == null) { throw new IllegalStateException("[galley] IP not found."); } return top.getHostAddress(); }
From source file:net.spfbl.core.Core.java
private static boolean isRouteable(String hostame) { try {/*from w ww . jav a2 s .co m*/ Attributes attributesA = Server.getAttributesDNS(hostame, new String[] { "A" }); Attribute attributeA = attributesA.get("A"); if (attributeA == null) { Attributes attributesAAAA = Server.getAttributesDNS(hostame, new String[] { "AAAA" }); Attribute attributeAAAA = attributesAAAA.get("AAAA"); if (attributeAAAA != null) { for (int i = 0; i < attributeAAAA.size(); i++) { String host6Address = (String) attributeAAAA.get(i); if (SubnetIPv6.isValidIPv6(host6Address)) { try { InetAddress address = InetAddress.getByName(host6Address); if (address.isLinkLocalAddress()) { return false; } else if (address.isLoopbackAddress()) { return false; } } catch (UnknownHostException ex) { } } else { return false; } } } } else { for (int i = 0; i < attributeA.size(); i++) { String host4Address = (String) attributeA.get(i); host4Address = host4Address.trim(); if (SubnetIPv4.isValidIPv4(host4Address)) { try { InetAddress address = InetAddress.getByName(host4Address); if (address.isLinkLocalAddress()) { return false; } else if (address.isLoopbackAddress()) { return false; } } catch (UnknownHostException ex) { } } else { return false; } } } return true; } catch (NamingException ex) { return false; } }
From source file:org.blue.star.plugins.check_ping.java
public boolean execute_check() { for (String hostname : addresses) { try {// w ww . ja va 2 s .c o m InetAddress inet = InetAddress.getByName(hostname); long execute_time = 0; long packet_loss = 0; for (int pings = 0; pings < max_packets; pings++) { boolean reachable = false; long ping_time = System.currentTimeMillis(); if (network_interface != null) { reachable = inet.isReachable(network_interface, 0, utils_h.timeout_interval); } else { reachable = inet.isReachable(utils_h.timeout_interval); } execute_time += (System.currentTimeMillis() - ping_time); if (!reachable) packet_loss++; } rta = execute_time / max_packets; pl = (int) packet_loss / max_packets * 100; if (verbose > 0) { System.out.println("rta = " + rta); System.out.println("pl = " + pl); } if (verbose > 1) { System.out.println("isAnyLocalAddress = " + inet.isAnyLocalAddress()); System.out.println("isLinkLocalAddress = " + inet.isLinkLocalAddress()); System.out.println("isLoopbackAddress = " + inet.isLoopbackAddress()); System.out.println("isMCGlobal = " + inet.isMCGlobal()); System.out.println("isMCLinkLocal = " + inet.isMCLinkLocal()); System.out.println("isMCNodeLocal = " + inet.isMCNodeLocal()); System.out.println("isMCOrgLocal = " + inet.isMCOrgLocal()); System.out.println("isMCSiteLocal = " + inet.isMCSiteLocal()); System.out.println("isMulticastAddress = " + inet.isMulticastAddress()); System.out.println("isSiteLocalAddress = " + inet.isSiteLocalAddress()); System.out.println("isReachable = " + inet.isReachable(utils_h.timeout_interval)); System.out.println("getCanonicalHostName = " + inet.getCanonicalHostName()); System.out.println("getHostAddress = " + inet.getHostAddress()); System.out.println("getHostName = " + inet.getHostName()); System.out.println("getClass.getName = " + inet.getClass().getName()); } /* The list is only used to check alternatives, if we pass don't do more */ if (packet_loss != max_packets) break; } catch (Exception e) { warn_text = e.getMessage(); e.printStackTrace(); } } if (pl >= cpl || rta >= crta || rta < 0) check_state = common_h.STATE_CRITICAL; else if (pl >= wpl || rta >= wrta) check_state = common_h.STATE_WARNING; else if (pl >= 0 && rta >= 0) check_state = common_h.STATE_OK; return true; }
From source file:com.httrack.android.HTTrackActivity.java
/** * Return the IPv6 address.//from www . j a va2 s. c o m * * @return The ipv6 address, or @c null if no IPv6 connectivity is available. */ protected static InetAddress getIPv6Address() { try { for (final Enumeration<NetworkInterface> interfaces = NetworkInterface .getNetworkInterfaces(); interfaces.hasMoreElements();) { final NetworkInterface iface = interfaces.nextElement(); for (final Enumeration<InetAddress> addresses = iface.getInetAddresses(); addresses .hasMoreElements();) { final InetAddress address = addresses.nextElement(); Log.d(HTTrackActivity.class.getSimpleName(), "seen interface: " + address.toString()); if (address instanceof Inet6Address) { if (!address.isLoopbackAddress() && !address.isLinkLocalAddress() && !address.isSiteLocalAddress() && !address.isMulticastAddress()) { return address; } } } } } catch (final SocketException se) { Log.w(HTTrackActivity.class.getSimpleName(), "could not enumerate interfaces", se); } return null; }