java.net.InetAddress#isSiteLocalAddress ( )源码实例Demo

下面列出了java.net.InetAddress#isSiteLocalAddress ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: codewind-eclipse   文件: PlatformUtil.java
public static String getHostName() throws SocketException {
  	Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
while(e.hasMoreElements())
{
    NetworkInterface n = (NetworkInterface) e.nextElement();
    Enumeration<InetAddress> ee = n.getInetAddresses();
    while (ee.hasMoreElements())
    {
        InetAddress i = (InetAddress) ee.nextElement();
        if (!i.isSiteLocalAddress() && !i.isLinkLocalAddress() && !i.isLoopbackAddress() && !i.isAnyLocalAddress() && !i.isMulticastAddress()) {
        	return i.getHostName();
        }
    }
}
throw new SocketException("Failed to get the IP address for the local host");
  }
 
源代码2 项目: react-native-sockets   文件: SocketsModule.java
@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);
}
 
源代码3 项目: diamond   文件: SystemConfig.java
private static String getHostAddress() {
    String address = "127.0.0.1";
    try {
        Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
        while (en.hasMoreElements()) {
            NetworkInterface ni = en.nextElement();
            Enumeration<InetAddress> ads = ni.getInetAddresses();
            while (ads.hasMoreElements()) {
                InetAddress ip = ads.nextElement();
                if (!ip.isLoopbackAddress() && ip.isSiteLocalAddress()) {
                    return ip.getHostAddress();
                }
            }
        }
    }
    catch (Exception e) {
    }
    return address;
}
 
源代码4 项目: blockchain   文件: CommonUtils.java
/**
 * 获得外网IP
 * 
 * @return 外网IP
 */
public static String getInternetIp() {
	try {
		Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
		InetAddress ip = null;
		Enumeration<InetAddress> addrs;
		while (networks.hasMoreElements()) {
			addrs = networks.nextElement().getInetAddresses();
			while (addrs.hasMoreElements()) {
				ip = addrs.nextElement();
				if (ip != null && ip instanceof Inet4Address && ip.isSiteLocalAddress()
						&& !ip.getHostAddress().equals(INTRANET_IP)) {
					return ip.getHostAddress();
				}
			}
		}

		// 如果没有外网IP,就返回内网IP
		return INTRANET_IP;
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
源代码5 项目: liteflow   文件: IpUtils.java
/**
 * 获取本地ip
 *
 * @return
 */
private static String getLocalIp() {
    try {
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces.nextElement();
            Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                InetAddress inetAddress = inetAddresses.nextElement();
                if (inetAddress.isSiteLocalAddress()) {
                    return inetAddress.getHostAddress();
                }
            }
        }
    } catch (Exception  e) {
        LOG.error("get local ip error!", e);
    }
    return null;
}
 
源代码6 项目: brave   文件: Platform.java
String produceLinkLocalIp() {
  try {
    Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
    while (nics.hasMoreElements()) {
      NetworkInterface nic = nics.nextElement();
      Enumeration<InetAddress> addresses = nic.getInetAddresses();
      while (addresses.hasMoreElements()) {
        InetAddress address = addresses.nextElement();
        if (address.isSiteLocalAddress()) return address.getHostAddress();
      }
    }
  } catch (Exception e) {
    // don't crash the caller if there was a problem reading nics.
    log("error reading nics", e);
  }
  return null;
}
 
源代码7 项目: jumbune   文件: AbstractCommandHandler.java
/**
 * Gets the current machine endpoint.
 *
 * @return the current machine endpoint
 * @throws SocketException the socket exception
 */
protected String getCurrentMachineEndpoint() throws SocketException {
	Enumeration<NetworkInterface> ifaces = NetworkInterface
			.getNetworkInterfaces();
	String ipAddress = null;
	for (NetworkInterface iface : Collections.list(ifaces)) {
		Enumeration<InetAddress> raddrs = iface.getInetAddresses();
		for (InetAddress raddr : Collections.list(raddrs)) {
			if (!raddr.isLoopbackAddress() && raddr.isSiteLocalAddress()) {
				if (raddr.toString().startsWith("/")) {
					ipAddress = raddr.toString().split("/")[1];
				}
			}
		}
	}
	return ipAddress;
}
 
源代码8 项目: spydroid-ipcamera   文件: Utilities.java
/**
 * Returns the IP address of the first configured interface of the device
 * @param removeIPv6 If true, IPv6 addresses are ignored
 * @return the IP address of the first configured interface or null
 */
public static String getLocalIpAddress(boolean removeIPv6) {
	try {
		for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
			NetworkInterface intf = en.nextElement();
			for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
				InetAddress inetAddress = enumIpAddr.nextElement();
				if (inetAddress.isSiteLocalAddress() &&
						!inetAddress.isAnyLocalAddress() &&
						(!removeIPv6 || isIpv4Address(inetAddress.getHostAddress().toString())) ) {
					return inetAddress.getHostAddress().toString();
				}
			}
		}
	} catch (SocketException ignore) {}
	return null;
}
 
源代码9 项目: yacy_grid_mcp   文件: Domains.java
private static boolean isLocal(final InetAddress a) {
    final boolean
        localp = noLocalCheck || // DO NOT REMOVE THIS! it is correct to return true if the check is off
        a == null ||
        a.isAnyLocalAddress() ||
        a.isLinkLocalAddress() ||
        a.isLoopbackAddress() ||
        a.isSiteLocalAddress();
    return localp;
}
 
源代码10 项目: flow   文件: AbstractTestBenchTest.java
private static Optional<String> getHostAddress(
        NetworkInterface nwInterface) {
    Enumeration<InetAddress> addresses = nwInterface.getInetAddresses();
    while (addresses.hasMoreElements()) {
        InetAddress address = addresses.nextElement();
        if (address.isLoopbackAddress()) {
            continue;
        }
        if (address.isSiteLocalAddress()) {
            return Optional.of(address.getHostAddress());
        }
    }
    return Optional.empty();
}
 
源代码11 项目: BACnet4J   文件: IpNetwork.java
public static InetAddress getDefaultLocalInetAddress() throws UnknownHostException, SocketException {
    for (NetworkInterface iface : Collections.list(NetworkInterface.getNetworkInterfaces())) {
        for (InetAddress addr : Collections.list(iface.getInetAddresses())) {
            if (!addr.isLoopbackAddress() && addr.isSiteLocalAddress())
                return addr;
        }
    }
    return InetAddress.getLocalHost();
}
 
源代码12 项目: wt1   文件: Utils.java
/**
 * Checks whether a String is a valid public IP address.
 */
public static boolean isPublicAddress(String a) {
	if (! InetAddresses.isInetAddress(a)) {
		return false;
	}
	InetAddress addr = InetAddresses.forString(a);
	return ! addr.isSiteLocalAddress()
			&& ! addr.isLinkLocalAddress()
			&& ! addr.isLoopbackAddress()
			&& ! addr.isAnyLocalAddress()
			&& ! addr.isMulticastAddress();
}
 
源代码13 项目: keycloak   文件: WelcomePageTest.java
/**
 * Attempt to resolve the floating IP address. This is where EAP/WildFly
 * will be accessible. See "-Djboss.bind.address=0.0.0.0".
 * 
 * @return
 * @throws Exception 
 */
private String getFloatingIpAddress() throws Exception {
    Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
    for (NetworkInterface ni : Collections.list(netInterfaces)) {
        Enumeration<InetAddress> inetAddresses = ni.getInetAddresses();
        for (InetAddress a : Collections.list(inetAddresses)) {
            if (!a.isLoopbackAddress() && a.isSiteLocalAddress()) {
                return a.getHostAddress();
            }
        }
    }
    return null;
}
 
源代码14 项目: leaf-snowflake   文件: Utils.java
/**
 * 获得外网IP
 * @return 外网IP
 */
public static String getInternetIp(){
	if( true )
		return getIntranetIp();
	try{
		Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
		InetAddress ip = null;
		Enumeration<InetAddress> addrs;
		while (networks.hasMoreElements())
		{
			addrs = networks.nextElement().getInetAddresses();
			while (addrs.hasMoreElements())
			{
				ip = addrs.nextElement();
				if (ip != null
						&& ip instanceof Inet4Address
						&& ip.isSiteLocalAddress()
						&& !ip.getHostAddress().equals(getIntranetIp()))
				{
					return ip.getHostAddress();
				}
			}
		}

		// 如果没有外网IP,就返回内网IP
		return getIntranetIp();
	} catch(Exception e){
		throw new RuntimeException(e);
	}
}
 
源代码15 项目: crate   文件: IfConfig.java
/** 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:").append(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:").append(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();
}
 
源代码16 项目: open-rmbt   文件: Helperfunctions.java
public static String filterIP(final 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";
        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";
    }
}
 
源代码17 项目: pampas   文件: AbstractServer.java
public InetAddress getLocalHostLANAddress() {
    try {
        InetAddress candidateAddress = null;
        // 遍历所有的网络接口
        for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements(); ) {
            NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
            // 在所有的接口下再遍历IP
            for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements(); ) {
                InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
                if (!inetAddr.isLoopbackAddress()) {// 排除loopback类型地址
                    if (inetAddr.isSiteLocalAddress()) {
                        // 如果是site-local地址,就是它了
                        return inetAddr;
                    } else if (candidateAddress == null) {
                        // site-local类型的地址未被发现,先记录候选地址
                        candidateAddress = inetAddr;
                    }
                }
            }
        }
        if (candidateAddress != null) {
            return candidateAddress;
        }
        // 如果没有发现 non-loopback地址.只能用最次选的方案
        InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
        return jdkSuppliedAddress;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
源代码18 项目: linden   文件: CommonUtils.java
public static String getLocalHostIp() {
  // for container env
  if (System.getenv(CONTAINER_ENV_KEY) != null && System.getenv(CONTAINER_ENV_KEY).equals("true")
      && System.getenv(HOST_IP_KEY) != null) {
    LOGGER.debug("Using the IP address {} from container env", System.getenv(HOST_IP_KEY));
    return System.getenv(HOST_IP_KEY);
  }

  try {
    for (NetworkInterface iface : Collections.list(NetworkInterface.getNetworkInterfaces())) {
      for (InetAddress addr : Collections.list(iface.getInetAddresses())) {
        LOGGER.debug("Checking ip address {}", addr);
        String hostAddress = addr.getHostAddress();
        // The docker virtual environment uses a virtual ip which should be skipped.
        if (addr.isSiteLocalAddress()
            && !addr.isLoopbackAddress()
            && !(addr instanceof Inet6Address)
            && !hostAddress.equals(DockerIP)) {
          LOGGER.debug("Ok, the ip {} will be used.", addr);
          return hostAddress;
        }
      }
    }
  } catch (SocketException e) {
    LOGGER.error("Couldn't find the local machine ip.", e);
  }
  throw new IllegalStateException("Couldn't find the local machine ip.");
}
 
源代码19 项目: blade-tool   文件: INetUtil.java
/**
 * https://stackoverflow.com/questions/9481865/getting-the-ip-address-of-the-current-machine-using-java
 *
 * <p>
 * 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.
 */
private static InetAddress getLocalHostLANAddress() throws UnknownHostException {
	try {
		InetAddress candidateAddress = null;
		// Iterate all NICs (network interface cards)...
		for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements(); ) {
			NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
			// Iterate all IP addresses assigned to each card...
			for (Enumeration 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;
	}
}
 
源代码20 项目: brooklyn-server   文件: Networking.java
/**
 * Check if this is a private address, not exposed on the public Internet.
 *
 * For IPV4 addresses this is an RFC1918 subnet (site local) address ({@code 10.0.0.0/8},
 * {@code 172.16.0.0/12} and {@code 192.168.0.0/16}), a link-local address
 * ({@code 169.254.0.0/16}) or a loopback address ({@code 127.0.0.1/0}).
 * <p>
 * For IPV6 addresses this is the RFC3514 link local block ({@code fe80::/10})
 * and site local block ({@code feco::/10}) or the loopback block
 * ({@code ::1/128}).
 *
 * @return true if the address is private
 */
public static boolean isPrivateSubnet(InetAddress address) {
    return address.isSiteLocalAddress() || address.isLoopbackAddress() || address.isLinkLocalAddress();
}