initCause ( )源码实例Demo

java.net.UnknownHostException#initCause ( )源码实例Demo

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

源代码1 项目: MHViewer   文件: EhDns.java
@Override
public List<InetAddress> lookup(String hostname) throws UnknownHostException {
  if (hostname == null) throw new UnknownHostException("hostname == null");

  InetAddress inetAddress = hosts.get(hostname);
  if (inetAddress != null) {
    return Collections.singletonList(inetAddress);
  }

  if (Settings.getBuiltInHosts()) {
    inetAddress = builtInHosts.get(hostname);
    if (inetAddress != null) {
      return Collections.singletonList(inetAddress);
    }
  }

  try {
    return Arrays.asList(InetAddress.getAllByName(hostname));
  } catch (NullPointerException e) {
    UnknownHostException unknownHostException =
        new UnknownHostException("Broken system behaviour for dns lookup of " + hostname);
    unknownHostException.initCause(e);
    throw unknownHostException;
  }
}
 
源代码2 项目: Mars-Java   文件: MarsAddressUtil.java
/**
 * 获取本服务的IP
 * @return ip
 * @throws UnknownHostException 异常
 */
public static InetAddress getLocalHostLANAddress() throws UnknownHostException {
    try {
        // 遍历所有的网络接口
        InetAddress candidateAddress = getLocalHost();
        if(candidateAddress != null){
            return candidateAddress;
        }

        // 如果没有发现 non-loopback地址.只能用最次选的方案
        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;
    }
}
 
源代码3 项目: EhViewer   文件: EhDns.java
@Override
public List<InetAddress> lookup(String hostname) throws UnknownHostException {
  if (hostname == null) throw new UnknownHostException("hostname == null");

  InetAddress inetAddress = hosts.get(hostname);
  if (inetAddress != null) {
    return Collections.singletonList(inetAddress);
  }

  if (Settings.getBuiltInHosts()) {
    inetAddress = builtInHosts.get(hostname);
    if (inetAddress != null) {
      return Collections.singletonList(inetAddress);
    }
  }

  try {
    return Arrays.asList(InetAddress.getAllByName(hostname));
  } catch (NullPointerException e) {
    UnknownHostException unknownHostException =
        new UnknownHostException("Broken system behaviour for dns lookup of " + hostname);
    unknownHostException.initCause(e);
    throw unknownHostException;
  }
}
 
源代码4 项目: Debug   文件: MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Debug.v("onCreate here!");
    Debug.d(1, 2, 3, 4, 5);
    Debug.i("0", "1", "2", "3"); // will just enumerate strings
    Debug.w("%s %s %s", null, null, null); // will call String.format
    Debug.e(true, null, Integer.MAX_VALUE, Long.MIN_VALUE);
    Debug.wtf("No, really, WTF?!");

    // lint in action
    Debug.i("%d", false);

    Debug.i("array: %s", new int[]{1, 2, 3, 4, 5});

    // Trace current method calls chain
    Debug.trace(100);

    final UnknownHostException exception = new UnknownHostException();
    exception.initCause(new Throwable());
    Debug.e(exception, "Hello this is a message for exception");
    Debug.e(exception);

    Debug.i("object as json: %s", json(this));
}
 
源代码5 项目: feeyo-hlsserver   文件: InetAddressUtil.java
private static InetAddress getLocalHostLANAddress() throws UnknownHostException {
    try {
        InetAddress candidateAddress = null;
        // 遍历所有的网络接口
        for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
            NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
            // 在所有的接口下再遍历IP
            for (Enumeration<InetAddress> 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();
        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;
    }
}
 
源代码6 项目: mica   文件: 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;
	}
}
 
源代码7 项目: 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;
	}
}
 
/**
 * Returns the {@link EndpointGroup} this client will connect to, derived from {@link #hosts()}.
 *
 * @throws UnknownHostException if failed to resolve the host names from the DNS servers
 */
protected final EndpointGroup endpointGroup() throws UnknownHostException {
    final Set<InetSocketAddress> hosts = hosts();
    checkState(!hosts.isEmpty(), "no hosts were added.");

    final InetSocketAddress firstHost = Iterables.getFirst(hosts, null);
    if (hosts.size() == 1 && !firstHost.isUnresolved()) {
        return toResolvedHostEndpoint(firstHost);
    }

    final List<Endpoint> staticEndpoints = new ArrayList<>();
    final List<EndpointGroup> groups = new ArrayList<>();
    for (final InetSocketAddress addr : hosts) {
        if (addr.isUnresolved()) {
            groups.add(DnsAddressEndpointGroup.builder(addr.getHostString())
                                              .eventLoop(clientFactory.eventLoopGroup().next())
                                              .port(addr.getPort())
                                              .build());
        } else {
            staticEndpoints.add(toResolvedHostEndpoint(addr));
        }
    }

    if (!staticEndpoints.isEmpty()) {
        groups.add(EndpointGroup.of(staticEndpoints));
    }

    final EndpointGroup group;
    if (groups.size() == 1) {
        group = groups.get(0);
    } else {
        group = new CompositeEndpointGroup(groups, EndpointSelectionStrategy.roundRobin());
    }

    if (group instanceof DynamicEndpointGroup) {
        // Wait until the initial endpointGroup list is ready.
        try {
            group.whenReady().get(10, TimeUnit.SECONDS);
        } catch (Exception e) {
            final UnknownHostException cause = new UnknownHostException(
                    "failed to resolve any of: " + hosts);
            cause.initCause(e);
            throw cause;
        }
    }

    if (!healthCheckInterval.isZero()) {
        return HealthCheckedEndpointGroup.builder(group, HttpApiV1Constants.HEALTH_CHECK_PATH)
                                         .clientFactory(clientFactory)
                                         .protocol(isUseTls() ? SessionProtocol.HTTPS
                                                              : SessionProtocol.HTTP)
                                         .retryInterval(healthCheckInterval)
                                         .build();
    } else {
        return group;
    }
}
 
源代码9 项目: ctsms   文件: CommonUtil.java
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;
	}
}
 
源代码10 项目: terracotta-platform   文件: ClientIdentifier.java
/**
 * http://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.
 */
static InetAddress discoverLANAddress() throws UnknownHostException {
  InetAddress inetAddress = InetAddress.getLocalHost();
  if (!inetAddress.isLoopbackAddress() && inetAddress.isSiteLocalAddress()) {
    return inetAddress;
  }

  try {
    InetAddress candidateAddress = null;
    // Iterate all NICs (network interface cards)...
    for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements(); ) {
      NetworkInterface iface = ifaces.nextElement();
      // Iterate all IP addresses assigned to each card...
      for (Enumeration<InetAddress> inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements(); ) {
        InetAddress inetAddr = 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;
  }
}
 
源代码11 项目: mobility-rpc   文件: NetworkUtil.java
/**
 * 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 java.net.UnknownHostException If the LAN address of the machine cannot be found.
 * @return The LAN address of the machine
 */
public 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;
    }
}
 
源代码12 项目: j2objc   文件: GaiException.java
/**
 * @hide - internal use only.
 */
public UnknownHostException rethrowAsUnknownHostException(String detailMessage) throws UnknownHostException {
  UnknownHostException newException = new UnknownHostException(detailMessage);
  newException.initCause(this);
  throw newException;
}
 
源代码13 项目: easyooo-framework   文件: InetAddressUtil.java
/**
 * 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.
 */
public 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 = ifaces.nextElement();
            // Iterate all IP addresses assigned to each card...
            for (Enumeration<InetAddress> inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
                InetAddress inetAddr = 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;
    }
}
 
源代码14 项目: commons-jcs   文件: HostNameUtil.java
/**
 * 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>
 * <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>
 * <a href="http://issues.apache.org/jira/browse/JCS-40">JIR ISSUE JCS-40</a>
 * <p>
 * @return InetAddress
 * @throws UnknownHostException If the LAN address of the machine cannot be found.
 */
public 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 = ifaces.nextElement();
            // Iterate all IP addresses assigned to each card...
            for ( Enumeration<InetAddress> inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements(); )
            {
                InetAddress inetAddr = 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 ( SocketException e )
    {
        UnknownHostException unknownHostException = new UnknownHostException( "Failed to determine LAN address: "
            + e );
        unknownHostException.initCause( e );
        throw unknownHostException;
    }
}
 
源代码评论
动弹
沙发等你来抢