List of usage examples for java.net InetAddress isSiteLocalAddress
public boolean isSiteLocalAddress()
From source file:org.springframework.cloud.commons.util.InetUtils.java
/** for testing */ boolean ignoreAddress(InetAddress address) { if (this.properties.isUseOnlySiteLocalInterfaces() && !address.isSiteLocalAddress()) { log.trace("Ignoring address: " + address.getHostAddress()); return true; }//from w ww . j a v a 2 s.c o m for (String regex : this.properties.getPreferredNetworks()) { if (!address.getHostAddress().matches(regex) && !address.getHostAddress().startsWith(regex)) { log.trace("Ignoring address: " + address.getHostAddress()); return true; } } return false; }
From source file:com.flexive.shared.stream.FxStreamUtils.java
/** * Probe all network interfaces and return the most suited to run a StreamServer on. * Preferred are interfaces that are not site local. * * @return best suited host to run a StreamServer * @throws UnknownHostException on errors *///from w w w . ja va 2 s . co m public static InetAddress probeNetworkInterfaces() throws UnknownHostException { try { final String forcedAddress = System.getProperty("FxStreamIP"); if (forcedAddress != null) { try { InetAddress ad = InetAddress.getByName(forcedAddress); LOG.info("Binding [fleXive] streamserver to forced address [" + forcedAddress + "] ..."); return ad; } catch (UnknownHostException e) { LOG.error("Forced [fleXive] streamserver bind address [" + forcedAddress + "] can not be used: " + e.getMessage() + " - probing available network interfaces ..."); } } Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces(); NetworkInterface nif; InetAddress preferred = null, fallback = null; while (nifs.hasMoreElements()) { nif = nifs.nextElement(); if (LOG.isDebugEnabled()) LOG.debug("Probing " + nif.getDisplayName() + " ..."); if (nif.getDisplayName().startsWith("vmnet") || nif.getDisplayName().startsWith("vnet")) continue; Enumeration<InetAddress> inas = nif.getInetAddresses(); while (inas.hasMoreElements()) { InetAddress na = inas.nextElement(); if (LOG.isDebugEnabled()) LOG.debug("Probing " + nif.getDisplayName() + na); if (!(na instanceof Inet4Address)) continue; if (!na.isLoopbackAddress() && na.isReachable(1000)) { if (preferred == null || (preferred.isSiteLocalAddress() && !na.isSiteLocalAddress())) preferred = na; } if (fallback == null && na.isLoopbackAddress()) fallback = na; } } if (LOG.isDebugEnabled()) LOG.debug("preferred: " + preferred + " fallback: " + fallback); if (preferred != null) return preferred; if (fallback != null) return fallback; return InetAddress.getLocalHost(); } catch (Exception e) { return InetAddress.getLocalHost(); } }
From source file:com.opensoc.enrichment.adapters.geo.GeoMysqlAdapter.java
@SuppressWarnings("unchecked") @Override//from www. j a v a 2 s . c o m public JSONObject enrich(String metadata) { ResultSet resultSet = null; try { _LOG.trace("[OpenSOC] Received metadata: " + metadata); InetAddress addr = InetAddress.getByName(metadata); if (addr.isAnyLocalAddress() || addr.isLoopbackAddress() || addr.isSiteLocalAddress() || addr.isMulticastAddress() || !ipvalidator.isValidInet4Address(metadata)) { _LOG.trace("[OpenSOC] Not a remote IP: " + metadata); _LOG.trace("[OpenSOC] Returning enrichment: " + "{}"); return new JSONObject(); } _LOG.trace("[OpenSOC] Is a valid remote IP: " + metadata); statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); String locid_query = "select IPTOLOCID(\"" + metadata + "\") as ANS"; resultSet = statement.executeQuery(locid_query); if (resultSet == null) throw new Exception( "Invalid result set for metadata: " + metadata + ". Query run was: " + locid_query); resultSet.last(); int size = resultSet.getRow(); if (size == 0) throw new Exception("No result returned for: " + metadata + ". Query run was: " + locid_query); resultSet.beforeFirst(); resultSet.next(); String locid = null; locid = resultSet.getString("ANS"); if (locid == null) throw new Exception("Invalid location id for: " + metadata + ". Query run was: " + locid_query); String geo_query = "select * from location where locID = " + locid + ";"; resultSet = statement.executeQuery(geo_query); if (resultSet == null) throw new Exception("Invalid result set for metadata and locid: " + metadata + ", " + locid + ". Query run was: " + geo_query); resultSet.last(); size = resultSet.getRow(); if (size == 0) throw new Exception("No result id returned for metadata and locid: " + metadata + ", " + locid + ". Query run was: " + geo_query); resultSet.beforeFirst(); resultSet.next(); JSONObject jo = new JSONObject(); jo.put("locID", resultSet.getString("locID")); jo.put("country", resultSet.getString("country")); jo.put("city", resultSet.getString("city")); jo.put("postalCode", resultSet.getString("postalCode")); jo.put("latitude", resultSet.getString("latitude")); jo.put("longitude", resultSet.getString("longitude")); jo.put("dmaCode", resultSet.getString("dmaCode")); jo.put("locID", resultSet.getString("locID")); jo.put("location_point", jo.get("longitude") + "," + jo.get("latitude")); _LOG.debug("Returning enrichment: " + jo); return jo; } catch (Exception e) { e.printStackTrace(); _LOG.error("Enrichment failure: " + e); return new JSONObject(); } }
From source file:org.apache.metron.enrichment.adapters.geo.GeoMysqlAdapter.java
@SuppressWarnings("unchecked") @Override/* ww w.jav a2 s . c o m*/ public JSONObject enrich(String metadata) { ResultSet resultSet = null; try { _LOG.trace("[Metron] Received metadata: " + metadata); InetAddress addr = InetAddress.getByName(metadata); if (addr.isAnyLocalAddress() || addr.isLoopbackAddress() || addr.isSiteLocalAddress() || addr.isMulticastAddress() || !ipvalidator.isValidInet4Address(metadata)) { _LOG.trace("[Metron] Not a remote IP: " + metadata); _LOG.trace("[Metron] Returning enrichment: " + "{}"); return new JSONObject(); } _LOG.trace("[Metron] Is a valid remote IP: " + metadata); statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); String locid_query = "select IPTOLOCID(\"" + metadata + "\") as ANS"; resultSet = statement.executeQuery(locid_query); if (resultSet == null) throw new Exception( "Invalid result set for metadata: " + metadata + ". Query run was: " + locid_query); resultSet.last(); int size = resultSet.getRow(); if (size == 0) throw new Exception("No result returned for: " + metadata + ". Query run was: " + locid_query); resultSet.beforeFirst(); resultSet.next(); String locid = null; locid = resultSet.getString("ANS"); if (locid == null) throw new Exception("Invalid location id for: " + metadata + ". Query run was: " + locid_query); String geo_query = "select * from location where locID = " + locid + ";"; resultSet = statement.executeQuery(geo_query); if (resultSet == null) throw new Exception("Invalid result set for metadata and locid: " + metadata + ", " + locid + ". Query run was: " + geo_query); resultSet.last(); size = resultSet.getRow(); if (size == 0) throw new Exception("No result id returned for metadata and locid: " + metadata + ", " + locid + ". Query run was: " + geo_query); resultSet.beforeFirst(); resultSet.next(); JSONObject jo = new JSONObject(); jo.put("locID", resultSet.getString("locID")); jo.put("country", resultSet.getString("country")); jo.put("city", resultSet.getString("city")); jo.put("postalCode", resultSet.getString("postalCode")); jo.put("latitude", resultSet.getString("latitude")); jo.put("longitude", resultSet.getString("longitude")); jo.put("dmaCode", resultSet.getString("dmaCode")); jo.put("locID", resultSet.getString("locID")); jo.put("location_point", jo.get("longitude") + "," + jo.get("latitude")); _LOG.debug("Returning enrichment: " + jo); return jo; } catch (Exception e) { e.printStackTrace(); _LOG.error("Enrichment failure: " + e); return new JSONObject(); } }
From source file:edu.ucsb.eucalyptus.ic.WalrusReplyQueue.java
public void handle(ExceptionMessage muleMsg) { try {/*from w ww . j ava 2 s.c om*/ Object requestMsg = muleMsg.getPayload(); String requestString = requestMsg.toString(); EucalyptusMessage msg = (EucalyptusMessage) BindingManager.getBinding("msgs_eucalyptus_ucsb_edu") .fromOM(requestString); Throwable ex = muleMsg.getException().getCause(); EucalyptusMessage errMsg; String ipAddr = "127.0.0.1"; List<NetworkInterface> ifaces = null; try { ifaces = Collections.list(NetworkInterface.getNetworkInterfaces()); } catch (SocketException e1) { } for (NetworkInterface iface : ifaces) { try { if (!iface.isLoopback() && !iface.isVirtual() && iface.isUp()) { for (InetAddress iaddr : Collections.list(iface.getInetAddresses())) { if (!iaddr.isSiteLocalAddress() && !(iaddr instanceof Inet6Address)) { ipAddr = iaddr.getHostAddress(); break; } } } } catch (SocketException e1) { } } if (ex instanceof NoSuchBucketException) { errMsg = new WalrusBucketErrorMessageType(((NoSuchBucketException) ex).getBucketName(), "NoSuchBucket", "The specified bucket was not found", HttpStatus.SC_NOT_FOUND, msg.getCorrelationId(), ipAddr); errMsg.setCorrelationId(msg.getCorrelationId()); } else if (ex instanceof AccessDeniedException) { errMsg = new WalrusBucketErrorMessageType(((AccessDeniedException) ex).getBucketName(), "AccessDenied", "No U", HttpStatus.SC_FORBIDDEN, msg.getCorrelationId(), ipAddr); errMsg.setCorrelationId(msg.getCorrelationId()); } else if (ex instanceof NotAuthorizedException) { errMsg = new WalrusBucketErrorMessageType(((NotAuthorizedException) ex).getValue(), "Unauthorized", "No U", HttpStatus.SC_UNAUTHORIZED, msg.getCorrelationId(), ipAddr); errMsg.setCorrelationId(msg.getCorrelationId()); } else if (ex instanceof BucketAlreadyOwnedByYouException) { errMsg = new WalrusBucketErrorMessageType(((BucketAlreadyOwnedByYouException) ex).getBucketName(), "BucketAlreadyOwnedByYou", "Your previous request to create the named bucket succeeded and you already own it.", HttpStatus.SC_CONFLICT, msg.getCorrelationId(), ipAddr); errMsg.setCorrelationId(msg.getCorrelationId()); } else if (ex instanceof BucketAlreadyExistsException) { errMsg = new WalrusBucketErrorMessageType(((BucketAlreadyExistsException) ex).getBucketName(), "BucketAlreadyExists", "The requested bucket name is not available. The bucket namespace is shared by all users of the system. Please select a different name and try again.", HttpStatus.SC_CONFLICT, msg.getCorrelationId(), ipAddr); errMsg.setCorrelationId(msg.getCorrelationId()); } else if (ex instanceof BucketNotEmptyException) { errMsg = new WalrusBucketErrorMessageType(((BucketNotEmptyException) ex).getBucketName(), "BucketNotEmpty", "The bucket you tried to delete is not empty.", HttpStatus.SC_CONFLICT, msg.getCorrelationId(), ipAddr); errMsg.setCorrelationId(msg.getCorrelationId()); } else if (ex instanceof PreconditionFailedException) { errMsg = new WalrusBucketErrorMessageType(((PreconditionFailedException) ex).getPrecondition(), "PreconditionFailed", "At least one of the pre-conditions you specified did not hold.", HttpStatus.SC_PRECONDITION_FAILED, msg.getCorrelationId(), ipAddr); errMsg.setCorrelationId(msg.getCorrelationId()); } else if (ex instanceof NotModifiedException) { errMsg = new WalrusBucketErrorMessageType(((NotModifiedException) ex).getPrecondition(), "NotModified", "Object Not Modified", HttpStatus.SC_NOT_MODIFIED, msg.getCorrelationId(), ipAddr); errMsg.setCorrelationId(msg.getCorrelationId()); } else if (ex instanceof TooManyBucketsException) { errMsg = new WalrusBucketErrorMessageType(((TooManyBucketsException) ex).getBucketName(), "TooManyBuckets", "You have attempted to create more buckets than allowed.", HttpStatus.SC_BAD_REQUEST, msg.getCorrelationId(), ipAddr); errMsg.setCorrelationId(msg.getCorrelationId()); } else if (ex instanceof EntityTooLargeException) { errMsg = new WalrusBucketErrorMessageType(((EntityTooLargeException) ex).getEntityName(), "EntityTooLarge", "Your proposed upload exceeds the maximum allowed object size.", HttpStatus.SC_BAD_REQUEST, msg.getCorrelationId(), ipAddr); errMsg.setCorrelationId(msg.getCorrelationId()); } else if (ex instanceof NoSuchEntityException) { errMsg = new WalrusBucketErrorMessageType(((NoSuchEntityException) ex).getBucketName(), "NoSuchEntity", "The specified entity was not found", HttpStatus.SC_NOT_FOUND, msg.getCorrelationId(), ipAddr); errMsg.setCorrelationId(msg.getCorrelationId()); } else if (ex instanceof DecryptionFailedException) { errMsg = new WalrusBucketErrorMessageType(((DecryptionFailedException) ex).getValue(), "Decryption Failed", "Fail", SC_DECRYPTION_FAILED, msg.getCorrelationId(), ipAddr); errMsg.setCorrelationId(msg.getCorrelationId()); } else if (ex instanceof ImageAlreadyExistsException) { errMsg = new WalrusBucketErrorMessageType(((ImageAlreadyExistsException) ex).getValue(), "Image Already Exists", "Fail", HttpStatus.SC_CONFLICT, msg.getCorrelationId(), ipAddr); errMsg.setCorrelationId(msg.getCorrelationId()); } else if (ex instanceof NotImplementedException) { errMsg = new WalrusBucketErrorMessageType(((NotImplementedException) ex).getValue(), "Not Implemented", "NA", HttpStatus.SC_NOT_IMPLEMENTED, msg.getCorrelationId(), ipAddr); errMsg.setCorrelationId(msg.getCorrelationId()); } else { errMsg = new EucalyptusErrorMessageType(muleMsg.getComponentName(), msg, ex.getMessage()); } replies.putMessage(errMsg); } catch (Exception e) { LOG.error(e, e); } }
From source file:nu.nethome.home.items.net.H2DatabaseTCPServer.java
public String getExternalIPAddress() { String result = null;/* w w w . j a v a 2s.c o m*/ Enumeration<NetworkInterface> interfaces2 = null; try { interfaces2 = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { logger.severe("Can't get network interfaces: " + e.getMessage()); return ""; } if (interfaces2 != null) { while (interfaces2.hasMoreElements() && StringUtils.isEmpty(result)) { NetworkInterface i = interfaces2.nextElement(); Enumeration<InetAddress> addresses2 = i.getInetAddresses(); while (addresses2.hasMoreElements() && (result == null || result.isEmpty())) { InetAddress address = addresses2.nextElement(); if (!address.isLoopbackAddress() && address.isSiteLocalAddress()) { result = address.getHostAddress(); } } } } return result; }
From source file:org.peercast.core.PeerCastServiceController.java
private String getIpAddress() { Enumeration<NetworkInterface> netIFs; try {//from w ww . jav a 2 s .co m netIFs = NetworkInterface.getNetworkInterfaces(); while (netIFs.hasMoreElements()) { NetworkInterface netIF = netIFs.nextElement(); Enumeration<InetAddress> ipAddrs = netIF.getInetAddresses(); while (ipAddrs.hasMoreElements()) { InetAddress ip = ipAddrs.nextElement(); if (!ip.isLoopbackAddress() && !ip.isLinkLocalAddress() && ip.isSiteLocalAddress()) { String ipStr = ip.getHostAddress().toString(); Log.d(TAG, "IP: " + ipStr); return ipStr; } } } } catch (SocketException e) { e.printStackTrace(); } 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 w w w.j ava2 s.c o 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.opendaylight.ovsdb.openstack.netvirt.impl.BridgeConfigurationManagerImpl.java
private String getControllerTarget() { /* TODO SB_MIGRATION * hardcoding value, need to find better way to get local ip *///w ww . ja va 2 s. c om //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:com.taobao.adfs.util.Utilities.java
public static List<InetAddress> getInetAddressList(List<InetAddress> addressList, String type) throws IOException { type = type.toLowerCase();// w w w . j av a2 s . c o m List<InetAddress> newAddressList = new ArrayList<InetAddress>(); for (InetAddress address : addressList) { if (address.isLinkLocalAddress()) { if (type.equals("linklocal")) newAddressList.add(address); } else if (address.isLoopbackAddress()) { if (type.equals("loopback")) newAddressList.add(address); } else if (address.isSiteLocalAddress()) { if (type.equals("lan")) newAddressList.add(address); } else { if (type.equals("wan")) newAddressList.add(address); } } Collections.sort(newAddressList, inetAddressComparator); return newAddressList; }