List of usage examples for java.net InetAddress isLoopbackAddress
public boolean isLoopbackAddress()
From source file:com.carreygroup.JARVIS.Demon.java
/** * Get IP address from first non-localhost interface * @param ipv4 true=return ipv4, false=return ipv6 * @return address or empty string// ww w. j a v a 2s.c o m */ public static String getLoaclIPAddress(boolean useIPv4) { try { 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 (useIPv4) { if (isIPv4) return sAddr; } else { if (!isIPv4) { int delim = sAddr.indexOf('%'); // drop ip6 port suffix return delim < 0 ? sAddr : sAddr.substring(0, delim); } } } } } } catch (Exception ex) { } // for now eat exceptions return ""; }
From source file:Main.java
public static String filterIP(final InetAddress inetAddress) { try {/* ww w . j a v a2 s. c o m*/ final String ipVersion; if (inetAddress instanceof Inet4Address) ipVersion = "ipv4"; else if (inetAddress instanceof Inet6Address) ipVersion = "ipv6"; else ipVersion = "ipv?"; if (inetAddress.isAnyLocalAddress()) return "wildcard"; if (inetAddress.isSiteLocalAddress()) return "site_local_" + ipVersion; if (inetAddress.isLinkLocalAddress()) return "link_local_" + ipVersion; if (inetAddress.isLoopbackAddress()) return "loopback_" + ipVersion; return inetAddress.getHostAddress(); } catch (final IllegalArgumentException e) { return "illegal_ip"; } }
From source file:password.pwm.util.Helper.java
public static void checkUrlAgainstWhitelist(final PwmApplication pwmApplication, final SessionLabel sessionLabel, final String inputURL) throws PwmOperationalException { LOGGER.trace(sessionLabel, "beginning test of requested redirect URL: " + inputURL); if (inputURL == null || inputURL.isEmpty()) { return;//w w w. ja va 2 s .com } final URI inputURI; try { inputURI = URI.create(inputURL); } catch (IllegalArgumentException e) { LOGGER.error(sessionLabel, "unable to parse requested redirect url '" + inputURL + "', error: " + e.getMessage()); // dont put input uri in error response final String errorMsg = "unable to parse url: " + e.getMessage(); throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_REDIRECT_ILLEGAL, errorMsg)); } { // check to make sure we werent handed a non-http uri. final String scheme = inputURI.getScheme(); if (scheme != null && !scheme.isEmpty() && !scheme.equalsIgnoreCase("http") && !scheme.equals("https")) { final String errorMsg = "unsupported url scheme"; throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_REDIRECT_ILLEGAL, errorMsg)); } } if (inputURI.getHost() != null && !inputURI.getHost().isEmpty()) { // disallow localhost uri try { InetAddress inetAddress = InetAddress.getByName(inputURI.getHost()); if (inetAddress.isLoopbackAddress()) { final String errorMsg = "redirect to loopback host is not permitted"; throw new PwmOperationalException( new ErrorInformation(PwmError.ERROR_REDIRECT_ILLEGAL, errorMsg)); } } catch (UnknownHostException e) { /* noop */ } } final StringBuilder sb = new StringBuilder(); if (inputURI.getScheme() != null) { sb.append(inputURI.getScheme()); sb.append("://"); } if (inputURI.getHost() != null) { sb.append(inputURI.getHost()); } if (inputURI.getPort() != -1) { sb.append(":"); sb.append(inputURI.getPort()); } if (inputURI.getPath() != null) { sb.append(inputURI.getPath()); } final String testURI = sb.toString(); LOGGER.trace(sessionLabel, "preparing to whitelist test parsed and decoded URL: " + testURI); final String REGEX_PREFIX = "regex:"; final List<String> whiteList = pwmApplication.getConfig() .readSettingAsStringArray(PwmSetting.SECURITY_REDIRECT_WHITELIST); for (final String loopFragment : whiteList) { if (loopFragment.startsWith(REGEX_PREFIX)) { try { final String strPattern = loopFragment.substring(REGEX_PREFIX.length(), loopFragment.length()); final Pattern pattern = Pattern.compile(strPattern); if (pattern.matcher(testURI).matches()) { LOGGER.debug(sessionLabel, "positive URL match for regex pattern: " + strPattern); return; } else { LOGGER.trace(sessionLabel, "negative URL match for regex pattern: " + strPattern); } } catch (Exception e) { LOGGER.error(sessionLabel, "error while testing URL match for regex pattern: '" + loopFragment + "', error: " + e.getMessage()); ; } } else { if (testURI.startsWith(loopFragment)) { LOGGER.debug(sessionLabel, "positive URL match for pattern: " + loopFragment); return; } else { LOGGER.trace(sessionLabel, "negative URL match for pattern: " + loopFragment); } } } final String errorMsg = testURI + " is not a match for any configured redirect whitelist, see setting: " + PwmSetting.SECURITY_REDIRECT_WHITELIST.toMenuLocationDebug(null, PwmConstants.DEFAULT_LOCALE); throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_REDIRECT_ILLEGAL, errorMsg)); }
From source file:edu.usc.pgroup.floe.utils.Utils.java
/** * returns the canonical host name. This assumes a unique host name for * each machine in the cluster does not apply. * FixMe: In local cloud environment (local eucalyptus in system mode) * where the DNS server is not running, this might be an issue. * @return The first IPv4 address found for any interface that is up and * running./*from w w w . j a va 2 s. c o m*/ */ public static String getIpAddress() { String ip = null; try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); LOGGER.error("Getting ip"); while (interfaces.hasMoreElements()) { LOGGER.error("Next iface"); NetworkInterface current = interfaces.nextElement(); if (!current.isUp() || current.isLoopback() || current.isVirtual()) { continue; } Enumeration<InetAddress> addresses = current.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress currentAddr = addresses.nextElement(); if (currentAddr.isLoopbackAddress() || (currentAddr instanceof Inet6Address)) { continue; } ip = currentAddr.getHostAddress(); } } } catch (SocketException e) { LOGGER.error("Error occurred while retrieving hostname" + e.getMessage()); throw new RuntimeException("Error occurred while " + "retrieving hostname" + e.getMessage()); } return ip; }
From source file:com.entertailion.android.slideshow.utils.Utils.java
public static final InetAddress getLocalInetAddress() { InetAddress selectedInetAddress = null; try {// w ww .ja v a 2 s . co m for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en .hasMoreElements();) { NetworkInterface intf = en.nextElement(); if (intf.isUp()) { for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr .hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { if (inetAddress instanceof Inet4Address) { // only // want // ipv4 // address if (inetAddress.getHostAddress().toString().charAt(0) != '0') { if (selectedInetAddress == null) { selectedInetAddress = inetAddress; } else if (intf.getName().startsWith("eth")) { // prefer // wired // interface selectedInetAddress = inetAddress; } } } } } } } return selectedInetAddress; } catch (Throwable e) { Log.e(LOG_TAG, "Failed to get the IP address", e); } return null; }
From source file:net.pms.network.UPNPHelper.java
/** * Gets the new multicast socket./*from w w w .j a v a2 s . c o m*/ * * @return the new multicast socket * @throws IOException Signals that an I/O exception has occurred. */ private static MulticastSocket getNewMulticastSocket() throws IOException { NetworkInterface networkInterface = NetworkConfiguration.getInstance().getNetworkInterfaceByServerName(); if (networkInterface == null) { networkInterface = PMS.get().getServer().getNetworkInterface(); } if (networkInterface == null) { throw new IOException("No usable network interface found for UPnP multicast"); } List<InetAddress> usableAddresses = new ArrayList<InetAddress>(); List<InetAddress> networkInterfaceAddresses = Collections.list(networkInterface.getInetAddresses()); for (InetAddress inetAddress : networkInterfaceAddresses) { if (inetAddress != null && inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) { usableAddresses.add(inetAddress); } } if (usableAddresses.isEmpty()) { throw new IOException("No usable addresses found for UPnP multicast"); } InetSocketAddress localAddress = new InetSocketAddress(usableAddresses.get(0), 0); MulticastSocket ssdpSocket = new MulticastSocket(localAddress); ssdpSocket.setReuseAddress(true); logger.trace( "Sending message from multicast socket on network interface: " + ssdpSocket.getNetworkInterface()); logger.trace("Multicast socket is on interface: " + ssdpSocket.getInterface()); ssdpSocket.setTimeToLive(32); logger.trace("Socket Timeout: " + ssdpSocket.getSoTimeout()); logger.trace("Socket TTL: " + ssdpSocket.getTimeToLive()); return ssdpSocket; }
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 *///w ww . j a va 2s. c o 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:org.apache.synapse.transport.nhttp.DefaultHttpGetProcessor.java
/** * Whatever this method returns as the IP is ignored by the actual http/s listener when * its getServiceEPR is invoked. This was originally copied from axis2 * * @return Returns String.//from w ww . ja va 2 s.c om * @throws java.net.SocketException if the socket can not be accessed */ protected static String getIpAddress() throws SocketException { Enumeration e = NetworkInterface.getNetworkInterfaces(); String address = "127.0.0.1"; while (e.hasMoreElements()) { NetworkInterface netface = (NetworkInterface) e.nextElement(); Enumeration addresses = netface.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress ip = (InetAddress) addresses.nextElement(); if (!ip.isLoopbackAddress() && isIP(ip.getHostAddress())) { return ip.getHostAddress(); } } } return address; }
From source file:org.apache.sshd.common.util.net.SshdSocketAddress.java
/** * @param addr The {@link InetAddress} to be considered * @return <code>true</code> if the address is a loopback one. * <B>Note:</B> if {@link InetAddress#isLoopbackAddress()} * returns <code>false</code> the address <U>string</U> is checked * @see #toAddressString(InetAddress)//from w w w . j a v a 2 s .co m * @see #isLoopback(String) */ public static boolean isLoopback(InetAddress addr) { if (addr == null) { return false; } if (addr.isLoopbackAddress()) { return true; } String ip = toAddressString(addr); return isLoopback(ip); }
From source file:com.petalmd.armor.AbstractUnitTest.java
public static String getNonLocalhostAddress() { try {// w w w .ja v a 2 s . c om for (final Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en .hasMoreElements();) { final NetworkInterface intf = en.nextElement(); if (intf.isLoopback() || !intf.isUp()) { continue; } for (final Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr .hasMoreElements();) { final InetAddress ia = enumIpAddr.nextElement(); if (ia.isLoopbackAddress() || ia instanceof Inet6Address) { continue; } return ia.getHostAddress(); } } } catch (final SocketException e) { throw new RuntimeException(e); } System.out.println("ERROR: No non-localhost address available, will use localhost"); return "localhost"; }