Java Code Examples for java.net.InetAddress.isSiteLocalAddress()

The following are Jave code examples for showing how to use isSiteLocalAddress() of the java.net.InetAddress class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: remote-storage-android-things   File: FTPManager.java   Source Code and License Vote up 6 votes
private String getLocalIpAddress() {
    String ipAddrrss = "";
    try {
        Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (enumNetworkInterfaces.hasMoreElements()) {
            Enumeration<InetAddress> enumInetAddress = enumNetworkInterfaces.nextElement().getInetAddresses();
            while (enumInetAddress.hasMoreElements()) {
                InetAddress inetAddress = enumInetAddress.nextElement();
                if (inetAddress.isSiteLocalAddress()) {
                    ipAddrrss = ipAddrrss + inetAddress.getHostAddress();
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
    return ipAddrrss;
}
 
Example 2
Project: react-native-sockets   File: SocketsModule.java   Source Code and License Vote up 6 votes
@ReactMethod
public void getIpAddress(Callback successCallback, Callback errorCallback) {
    WritableArray ipList = Arguments.createArray();
    try {
        Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (enumNetworkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = enumNetworkInterfaces.nextElement();
            Enumeration<InetAddress> enumInetAddress = networkInterface.getInetAddresses();
            while (enumInetAddress.hasMoreElements()) {
                InetAddress inetAddress = enumInetAddress.nextElement();
                if (inetAddress.isSiteLocalAddress()) {
                    ipList.pushString(inetAddress.getHostAddress());
                }
            }
        }
    } catch (SocketException e) {
        Log.e(eTag, "getIpAddress SocketException", e);
        errorCallback.invoke(e.getMessage());
    }
    successCallback.invoke(ipList);
}
 
Example 3
Project: BiglyBT   File: NetStatusPluginTester.java   Source Code and License Vote up 6 votes
protected void
addPublicAddress(
	Set<InetAddress>	addresses,
	InetAddress			address )
{
	if ( address == null ){

		return;
	}

	if ( 	address.isAnyLocalAddress() ||
			address.isLoopbackAddress() ||
			address.isLinkLocalAddress()||
			address.isSiteLocalAddress()){

			return;
	}

	addresses.add( address );
}
 
Example 4
Project: fdt   File: LocalHost.java   Source Code and License Vote up 6 votes
static public String getPublicIP4() {

        Enumeration<NetworkInterface> ifs;
        try {
            ifs = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            e.printStackTrace();
            return null;
        }

        while (ifs.hasMoreElements()) {
            NetworkInterface iface = ifs.nextElement();
            Enumeration<InetAddress> iad = iface.getInetAddresses();
            while (iad.hasMoreElements()) {
                InetAddress localIP = iad.nextElement();
                if (!localIP.isSiteLocalAddress() && !localIP.isLoopbackAddress()) {
                    // found an IPv4 address
                    if (localIP instanceof java.net.Inet4Address)
                        return localIP.getHostAddress();
                }
            }
        }
        return null;
    }
 
Example 5
Project: emergentmud   File: MainResource.java   Source Code and License Vote up 6 votes
private String extractRemoteIp(HttpServletRequest request) {
    String forwardedHeader = request.getHeader("x-forwarded-for");

    if (forwardedHeader != null) {
        String[] addresses = forwardedHeader.split("[,]");

        for (String address : addresses) {
            try {
                InetAddress inetAddress = InetAddress.getByName(address);

                if (!inetAddress.isSiteLocalAddress()) {
                    return inetAddress.getHostAddress();
                }
            } catch (UnknownHostException e) {
                LOGGER.debug("Failed to resolve IP for address: {}", address);
            }
        }
    }

    return request.getRemoteAddr();
}
 
Example 6
Project: aos-FileCoreLibrary   File: SambaDiscovery.java   Source Code and License Vote up 6 votes
private List<String> initIpAdresses() {
    List<String> result = new ArrayList<String>(2);
    String ip = initIpAddress();
    if (ip != null)
        result.add(ip);
    int intIpAddress = findDoubleNatIp();
    if (intIpAddress != 0) {
        byte[] bytes = BigInteger.valueOf(intIpAddress).toByteArray();
        InetAddress address = null;
        try {
            address = InetAddress.getByAddress(bytes);
        } catch (UnknownHostException ignored) {}
        if (address != null && address.isSiteLocalAddress())
            result.add(address.getHostAddress());
    }
    return result;
}
 
Example 7
Project: BloomReader   File: NewBookListenerService.java   Source Code and License Vote up 6 votes
private String getOurIpAddress() {
    String ip = "";
    try {
        Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (enumNetworkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = enumNetworkInterfaces.nextElement();
            Enumeration<InetAddress> enumInetAddress = networkInterface.getInetAddresses();
            while (enumInetAddress.hasMoreElements()) {
                InetAddress inetAddress = enumInetAddress.nextElement();

                if (inetAddress.isSiteLocalAddress()) {
                    return inetAddress.getHostAddress();
                }

            }

        }

    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        ip += "Something Wrong! " + e.toString() + "\n";
    }

    return ip;
}
 
Example 8
Project: elasticsearch_my   File: NetworkUtils.java   Source Code and License Vote up 6 votes
/** Returns all site-local scope (private) addresses for interfaces that are up. */
static InetAddress[] getSiteLocalAddresses() throws SocketException {
    List<InetAddress> list = new ArrayList<>();
    for (NetworkInterface intf : getInterfaces()) {
        if (intf.isUp()) {
            for (InetAddress address : Collections.list(intf.getInetAddresses())) {
                if (address.isSiteLocalAddress()) {
                    list.add(address);
                }
            }
        }
    }
    if (list.isEmpty()) {
        throw new IllegalArgumentException("No up-and-running site-local (private) addresses found, got " + getInterfaces());
    }
    return list.toArray(new InetAddress[list.size()]);
}
 
Example 9
Project: elasticsearch_my   File: NetworkUtils.java   Source Code and License Vote up 6 votes
/** Returns all global scope addresses for interfaces that are up. */
static InetAddress[] getGlobalAddresses() throws SocketException {
    List<InetAddress> list = new ArrayList<>();
    for (NetworkInterface intf : getInterfaces()) {
        if (intf.isUp()) {
            for (InetAddress address : Collections.list(intf.getInetAddresses())) {
                if (address.isLoopbackAddress() == false && 
                    address.isSiteLocalAddress() == false &&
                    address.isLinkLocalAddress() == false) {
                    list.add(address);
                }
            }
        }
    }
    if (list.isEmpty()) {
        throw new IllegalArgumentException("No up-and-running global-scope (public) addresses found, got " + getInterfaces());
    }
    return list.toArray(new InetAddress[list.size()]);
}
 
Example 10
Project: elephant   File: IPHelper.java   Source Code and License Vote up 5 votes
public static String getRealIp() {
	String localip = null;// 本地IP,如果没有配置外网IP则返回它
	String netip = null;// 外网IP
	try {
		Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
		InetAddress ip = null;
		boolean finded = false;//是否找到外网IP
		while (netInterfaces.hasMoreElements() && !finded) {
			NetworkInterface ni = netInterfaces.nextElement();
			Enumeration<InetAddress> address = ni.getInetAddresses();
			while (address.hasMoreElements()) {
				ip = address.nextElement();
				if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
						&& !ip.getHostAddress().contains(":")) {// 外网IP
					netip = ip.getHostAddress();
					finded = true;
					break;
				} else if (ip.isSiteLocalAddress()
						&& !ip.isLoopbackAddress()
						&& !ip.getHostAddress().contains(":")) {// 内网IP
					localip = ip.getHostAddress();
				}
			}
		}

		if (netip != null && !"".equals(netip)) {
			return netip;
		} else {
			return localip;
		}
	} catch (SocketException e) {
		logger.error("获取本机Ip失败:异常信息:" + e.getMessage());
		throw new RuntimeException(e);
	}
}
 
Example 11
Project: MCLibrary   File: ServerHostnameGetter.java   Source Code and License Vote up 5 votes
@EventHandler
public void onLogin(PlayerLoginEvent event) throws UnknownHostException {
    String host = event.getHostname();
    String addrStr = host.substring(0, host.indexOf(':'));
    InetAddress addr = InetAddress.getByName(addrStr);
    if (!addr.isLoopbackAddress() && !addr.isSiteLocalAddress()) {
        MCLibrary.setAddress(host);
        event.getHandlers().unregister(this);
    }
}
 
Example 12
Project: elasticsearch_my   File: IfConfig.java   Source Code and License Vote up 5 votes
/** format internet address: java's default doesn't include everything useful */
private static String formatAddress(InterfaceAddress interfaceAddress) throws IOException {
    StringBuilder sb = new StringBuilder();

    InetAddress address = interfaceAddress.getAddress();
    if (address instanceof Inet6Address) {
        sb.append("inet6 ");
        sb.append(NetworkAddress.format(address));
        sb.append(" prefixlen:");
        sb.append(interfaceAddress.getNetworkPrefixLength());
    } else {
        sb.append("inet ");
        sb.append(NetworkAddress.format(address));
        int netmask = 0xFFFFFFFF << (32 - interfaceAddress.getNetworkPrefixLength());
        sb.append(" netmask:" + NetworkAddress.format(InetAddress.getByAddress(new byte[] {
                (byte)(netmask >>> 24),
                (byte)(netmask >>> 16 & 0xFF),
                (byte)(netmask >>> 8 & 0xFF),
                (byte)(netmask & 0xFF)
        })));
        InetAddress broadcast = interfaceAddress.getBroadcast();
        if (broadcast != null) {
            sb.append(" broadcast:" + NetworkAddress.format(broadcast));
        }
    }
    if (address.isLoopbackAddress()) {
        sb.append(" scope:host");
    } else if (address.isLinkLocalAddress()) {
        sb.append(" scope:link");
    } else if (address.isSiteLocalAddress()) {
        sb.append(" scope:site");
    }
    return sb.toString();
}
 
Example 13
Project: Nird2   File: PrivacyUtils.java   Source Code and License Vote up 5 votes
@Nullable
public static String scrubInetAddress(InetAddress address) {
	// don't scrub link and site local addresses
	if (address.isLinkLocalAddress() || address.isSiteLocalAddress())
		return address.toString();
	// completely scrub IPv6 addresses
	if (address instanceof Inet6Address) return "[scrubbed]";
	// keep first and last octet of IPv4 addresses
	return scrubInetAddress(address.toString());
}
 
Example 14
Project: open-rmbt   File: Helperfunctions.java   Source Code and License Vote up 5 votes
public static String IpType(InetAddress inetAddress)
{
    try
    {
        final String ipVersion;
        if (inetAddress instanceof Inet4Address)
            ipVersion = "ipv4";
        else if (inetAddress instanceof Inet6Address)
            ipVersion = "ipv6";
        else
            ipVersion = "ipv?";
        
        if (inetAddress.isAnyLocalAddress())
            return "wildcard_" + ipVersion;
        if (inetAddress.isSiteLocalAddress())
            return "site_local_" + ipVersion;
        if (inetAddress.isLinkLocalAddress())
            return "link_local_" + ipVersion;
        if (inetAddress.isLoopbackAddress())
            return "loopback_" + ipVersion;
        return "public_" + ipVersion;

    }
    catch (final IllegalArgumentException e)
    {
        return "illegal_ip";
    }
}
 
Example 15
Project: Elasticsearch   File: IfConfig.java   Source Code and License Vote up 5 votes
/** format internet address: java's default doesn't include everything useful */
private static String formatAddress(InterfaceAddress interfaceAddress) throws IOException {
    StringBuilder sb = new StringBuilder();
    
    InetAddress address = interfaceAddress.getAddress();
    if (address instanceof Inet6Address) {
        sb.append("inet6 ");
        sb.append(NetworkAddress.formatAddress(address));
        sb.append(" prefixlen:");
        sb.append(interfaceAddress.getNetworkPrefixLength());
    } else {
        sb.append("inet ");
        sb.append(NetworkAddress.formatAddress(address));
        int netmask = 0xFFFFFFFF << (32 - interfaceAddress.getNetworkPrefixLength());
        sb.append(" netmask:" + NetworkAddress.formatAddress(InetAddress.getByAddress(new byte[] {
                (byte)(netmask >>> 24), 
                (byte)(netmask >>> 16 & 0xFF), 
                (byte)(netmask >>> 8 & 0xFF), 
                (byte)(netmask & 0xFF) 
        })));
        InetAddress broadcast = interfaceAddress.getBroadcast();
        if (broadcast != null) {
            sb.append(" broadcast:" + NetworkAddress.formatAddress(broadcast));
        }
    }
    if (address.isLoopbackAddress()) {
        sb.append(" scope:host");
    } else if (address.isLinkLocalAddress()) {
        sb.append(" scope:link");
    } else if (address.isSiteLocalAddress()) {
        sb.append(" scope:site");
    }
    return sb.toString();
}
 
Example 16
Project: Nird2   File: LanTcpPluginTest.java   Source Code and License Vote up 5 votes
private boolean systemHasLocalIpv4Address() throws Exception {
	for (NetworkInterface i : Collections.list(
			NetworkInterface.getNetworkInterfaces())) {
		for (InetAddress a : Collections.list(i.getInetAddresses())) {
			if (a instanceof Inet4Address)
				return a.isLinkLocalAddress() || a.isSiteLocalAddress();
		}
	}
	return false;
}
 
Example 17
Project: Nird2   File: WanTcpPlugin.java   Source Code and License Vote up 5 votes
private boolean isAcceptableAddress(InetAddress a) {
	// Accept global IPv4 addresses
	boolean ipv4 = a instanceof Inet4Address;
	boolean loop = a.isLoopbackAddress();
	boolean link = a.isLinkLocalAddress();
	boolean site = a.isSiteLocalAddress();
	return ipv4 && !loop && !link && !site;
}
 
Example 18
Project: VASSAL-src   File: ServerAddressBook.java   Source Code and License Vote up 4 votes
/**
 * Returns an <code>InetAddress</code> object encapsulating what is most likely the machine's LAN IP address.
 * <p/>
 * This method is intended for use as a replacement of JDK method <code>InetAddress.getLocalHost</code>, because
 * that method is ambiguous on Linux systems. Linux systems enumerate the loopback network interface the same
 * way as regular LAN network interfaces, but the JDK <code>InetAddress.getLocalHost</code> method does not
 * specify the algorithm used to select the address returned under such circumstances, and will often return the
 * loopback address, which is not valid for network communication. Details
 * <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4665037">here</a>.
 * <p/>
 * This method will scan all IP addresses on all network interfaces on the host machine to determine the IP address
 * most likely to be the machine's LAN address. If the machine has multiple IP addresses, this method will prefer
 * a site-local IP address (e.g. 192.168.x.x or 10.10.x.x, usually IPv4) if the machine has one (and will return the
 * first site-local address if the machine has more than one), but if the machine does not hold a site-local
 * address, this method will return simply the first non-loopback address found (IPv4 or IPv6).
 * <p/>
 * If this method cannot find a non-loopback address using this selection algorithm, it will fall back to
 * calling and returning the result of JDK method <code>InetAddress.getLocalHost</code>.
 * <p/>
 *
 * @throws UnknownHostException If the LAN address of the machine cannot be found.
 *
 * Thanks to https://issues.apache.org/jira/browse/JCS-40 for this code
 */
private static InetAddress getLocalHostLANAddress() throws UnknownHostException {
    try {
        InetAddress candidateAddress = null;
        // Iterate all NICs (network interface cards)...
        for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
            NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
            // Iterate all IP addresses assigned to each card...
            for (Enumeration<InetAddress> inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
                InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
                if (!inetAddr.isLoopbackAddress()) {

                    if (inetAddr.isSiteLocalAddress()) {
                        // Found non-loopback site-local address. Return it immediately...
                        return inetAddr;
                    }
                    else if (candidateAddress == null) {
                        // Found non-loopback address, but not necessarily site-local.
                        // Store it as a candidate to be returned if site-local address is not subsequently found...
                        candidateAddress = inetAddr;
                        // Note that we don't repeatedly assign non-loopback non-site-local addresses as candidates,
                        // only the first. For subsequent iterations, candidate will be non-null.
                    }
                }
            }
        }
        if (candidateAddress != null) {
            // We did not find a site-local address, but we found some other non-loopback address.
            // Server might have a non-site-local address assigned to its NIC (or it might be running
            // IPv6 which deprecates the "site-local" concept).
            // Return this non-loopback candidate address...
            return candidateAddress;
        }
        // At this point, we did not find a non-loopback address.
        // Fall back to returning whatever InetAddress.getLocalHost() returns...
        InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
        if (jdkSuppliedAddress == null) {
            throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
        }
        return jdkSuppliedAddress;
    }
    catch (Exception e) {
        UnknownHostException unknownHostException = new UnknownHostException("Failed to determine LAN address: " + e);
        unknownHostException.initCause(e);
        throw unknownHostException;
    }
}
 
Example 19
Project: elastic-job-cloud   File: IpUtils.java   Source Code and License Vote up 4 votes
private static boolean isPublicIpAddress(final InetAddress ipAddress) {
    return !ipAddress.isSiteLocalAddress() && !ipAddress.isLoopbackAddress() && !isV6IpAddress(ipAddress);
}
 
Example 20
Project: BiglyBT   File: PlatformTorrentUtils.java   Source Code and License Vote up 3 votes
public static boolean isPlatformHost(String host) {
	Object[] domains = getPlatformHosts().toArray();

	host = host.toLowerCase();

	for (int i = 0; i < domains.length; i++) {

		String domain = (String) domains[i];

		if (domain.equals(host)) {

			return (true);
		}

		if (host.endsWith("." + domain)) {

			return (true);
		}
	}

	if ( Constants.isCVSVersion()){

			// allow local addresses for testing

		try{
			InetAddress ia = InetAddress.getByName( host );

			return( ia.isLoopbackAddress() || ia.isLinkLocalAddress() || ia.isSiteLocalAddress());

		}catch( Throwable e ){
		}
	}

	return (false);
}