Java Code Examples for java.net.InetAddress#isAnyLocalAddress()

The following examples show how to use java.net.InetAddress#isAnyLocalAddress() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NetworkUtils.java    From crate with Apache License 2.0 6 votes vote down vote up
/** Sorts an address by preference. This way code like publishing can just pick the first one */
static int sortKey(InetAddress address, boolean prefer_v6) {
    int key = address.getAddress().length;
    if (prefer_v6) {
        key = -key;
    }

    if (address.isAnyLocalAddress()) {
        key += 5;
    }
    if (address.isMulticastAddress()) {
        key += 4;
    }
    if (address.isLoopbackAddress()) {
        key += 3;
    }
    if (address.isLinkLocalAddress()) {
        key += 2;
    }
    if (address.isSiteLocalAddress()) {
        key += 1;
    }

    return key;
}
 
Example 2
Source File: WebAppUtils.java    From big-c with Apache License 2.0 6 votes vote down vote up
private static String getResolvedAddress(InetSocketAddress address) {
  address = NetUtils.getConnectAddress(address);
  StringBuilder sb = new StringBuilder();
  InetAddress resolved = address.getAddress();
  if (resolved == null || resolved.isAnyLocalAddress() ||
      resolved.isLoopbackAddress()) {
    String lh = address.getHostName();
    try {
      lh = InetAddress.getLocalHost().getCanonicalHostName();
    } catch (UnknownHostException e) {
      //Ignore and fallback.
    }
    sb.append(lh);
  } else {
    sb.append(address.getHostName());
  }
  sb.append(":").append(address.getPort());
  return sb.toString();
}
 
Example 3
Source File: NanoHTTPD.java    From Lanmitm with GNU General Public License v2.0 5 votes vote down vote up
public HTTPSession(TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream, InetAddress inetAddress) {
    this.tempFileManager = tempFileManager;
    this.inputStream = new PushbackInputStream(inputStream, BUFSIZE);
    this.outputStream = outputStream;
    String remoteIp = inetAddress.isLoopbackAddress() || inetAddress.isAnyLocalAddress() ? "127.0.0.1" : inetAddress.getHostAddress().toString();
    headers = new HashMap<String, String>();

    headers.put("remote-addr", remoteIp);
    headers.put("http-client-ip", remoteIp);
}
 
Example 4
Source File: DeviceUtils.java    From TvPlayer with Apache License 2.0 5 votes vote down vote up
/**
 * 获取当前系统连接网络的网卡的mac地址
 *
 * @return
 */
public static final String getMac() {
    byte[] mac = null;
    StringBuffer sb = new StringBuffer();
    try {
        Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
        while (netInterfaces.hasMoreElements()) {
            NetworkInterface ni = netInterfaces.nextElement();
            Enumeration<InetAddress> address = ni.getInetAddresses();

            while (address.hasMoreElements()) {
                InetAddress ip = address.nextElement();
                if (ip.isAnyLocalAddress() || !(ip instanceof Inet4Address) || ip.isLoopbackAddress())
                    continue;
                if (ip.isSiteLocalAddress())
                    mac = ni.getHardwareAddress();
                else if (!ip.isLinkLocalAddress()) {
                    mac = ni.getHardwareAddress();
                    break;
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }

    if (mac != null) {
        for (int i = 0; i < mac.length; i++) {
            sb.append(parseByte(mac[i]));
        }
    }else{
        return "";
    }
    return sb.substring(0, sb.length() - 1);
}
 
Example 5
Source File: ActivitySettings.java    From NetGuard with GNU General Public License v3.0 5 votes vote down vote up
private void checkAddress(String address, boolean allow_local) throws IllegalArgumentException, UnknownHostException {
    if (address != null)
        address = address.trim();
    if (TextUtils.isEmpty(address))
        throw new IllegalArgumentException("Bad address");
    if (!Util.isNumericAddress(address))
        throw new IllegalArgumentException("Bad address");
    if (!allow_local) {
        InetAddress iaddr = InetAddress.getByName(address);
        if (iaddr.isLoopbackAddress() || iaddr.isAnyLocalAddress())
            throw new IllegalArgumentException("Bad address");
    }
}
 
Example 6
Source File: AddressUtils.java    From dhcp4j with Apache License 2.0 5 votes vote down vote up
/**
 * Determines whether the given address is a "useful" unicast address.
 *
 * Site local is allowed. Loopback is not.
 */
public static boolean isUnicastAddress(@CheckForNull InetAddress address) {
    return (address != null)
            && !address.isAnyLocalAddress()
            && !address.isLoopbackAddress()
            && !address.isMulticastAddress();
}
 
Example 7
Source File: NanoHTTPD.java    From LiveMultimedia with Apache License 2.0 5 votes vote down vote up
public HTTPSession(TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream, InetAddress inetAddress) {
    this.tempFileManager = tempFileManager;
    this.inputStream = new PushbackInputStream(inputStream, BUFSIZE);
    this.outputStream = outputStream;
    String remoteIp = inetAddress.isLoopbackAddress() || inetAddress.isAnyLocalAddress() ? "127.0.0.1" : inetAddress.getHostAddress().toString();
    headers = new HashMap<>();

    headers.put("remote-addr", remoteIp);
    headers.put("http-client-ip", remoteIp);
}
 
Example 8
Source File: ValidatorController.java    From validator-badge with Apache License 2.0 5 votes vote down vote up
private String getUrlContents(String urlString, boolean rejectLocal, boolean rejectRedirect) throws IOException {
    LOGGER.trace("fetching URL contents");
    URL url = new URL(urlString);
    if(rejectLocal) {
        InetAddress inetAddress = InetAddress.getByName(url.getHost());
        if(inetAddress.isAnyLocalAddress() || inetAddress.isLoopbackAddress() || inetAddress.isLinkLocalAddress()) {
            throw new IOException("Only accepts http/https protocol");
        }
    }
    final CloseableHttpClient httpClient = getCarelessHttpClient(rejectRedirect);

    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder
            .setConnectTimeout(5000)
            .setSocketTimeout(5000);

    HttpGet getMethod = new HttpGet(urlString);
    getMethod.setConfig(requestBuilder.build());
    getMethod.setHeader("Accept", "application/json, */*");


    if (httpClient != null) {
        final CloseableHttpResponse response = httpClient.execute(getMethod);

        try {

            HttpEntity entity = response.getEntity();
            StatusLine line = response.getStatusLine();
            if(line.getStatusCode() > 299 || line.getStatusCode() < 200) {
                throw new IOException("failed to read swagger with code " + line.getStatusCode());
            }
            return EntityUtils.toString(entity, "UTF-8");
        } finally {
            response.close();
            httpClient.close();
        }
    } else {
        throw new IOException("CloseableHttpClient could not be initialized");
    }
}
 
Example 9
Source File: Atlas.java    From atlas with Apache License 2.0 5 votes vote down vote up
private static boolean isLocalAddress(InetAddress addr) {
    // Check if the address is any local or loop back
    boolean local = addr.isAnyLocalAddress() || addr.isLoopbackAddress();

    // Check if the address is defined on any interface
    if (!local) {
        try {
            local = NetworkInterface.getByInetAddress(addr) != null;
        } catch (SocketException e) {
            local = false;
        }
    }
    return local;
}
 
Example 10
Source File: NetUtils.java    From RDFS with Apache License 2.0 5 votes vote down vote up
public static boolean isLocalAddress(InetAddress addr) {
  // Check if the address is any local or loop back
  boolean local = addr.isAnyLocalAddress() || addr.isLoopbackAddress();
  // Check if the address is defined on any interface
  if (!local) {
    try {
      local = NetworkInterface.getByInetAddress(addr) != null;
    } catch (SocketException e) {
      local = false;
    }
  }   
  return local;
}
 
Example 11
Source File: ActivitySettings.java    From tracker-control-android with GNU General Public License v3.0 5 votes vote down vote up
private void checkAddress(String address, boolean allow_local) throws IllegalArgumentException, UnknownHostException {
    if (address != null)
        address = address.trim();
    if (TextUtils.isEmpty(address))
        throw new IllegalArgumentException("Bad address");
    if (!Util.isNumericAddress(address))
        throw new IllegalArgumentException("Bad address");
    if (!allow_local) {
        InetAddress iaddr = InetAddress.getByName(address);
        if (iaddr.isLoopbackAddress() || iaddr.isAnyLocalAddress())
            throw new IllegalArgumentException("Bad address");
    }
}
 
Example 12
Source File: AddressUtils.java    From bt with Apache License 2.0 5 votes vote down vote up
public static boolean isGlobalUnicast(InetAddress addr)
{
	// local identification block
	if(addr instanceof Inet4Address && addr.getAddress()[0] == 0)
		return false;
	// this would be rejected by a socket with broadcast disabled anyway, but filter it to reduce exceptions
	if(addr instanceof Inet4Address && java.util.Arrays.equals(addr.getAddress(), LOCAL_BROADCAST))
		return false;
	if(addr instanceof Inet6Address && (addr.getAddress()[0] & 0xfe) == 0xfc) // fc00::/7
		return false;
	if(addr instanceof Inet6Address && (V4_MAPPED.contains(addr) || V4_COMPAT.contains(addr)))
		return false;
	return !(addr.isAnyLocalAddress() || addr.isLinkLocalAddress() || addr.isLoopbackAddress() || addr.isMulticastAddress() || addr.isSiteLocalAddress());
}
 
Example 13
Source File: ProxyServer.java    From odo with Apache License 2.0 5 votes vote down vote up
public void setLocalHost(InetAddress localHost) throws SocketException {
    if (localHost.isAnyLocalAddress() ||
        localHost.isLoopbackAddress() ||
        NetworkInterface.getByInetAddress(localHost) != null)
    {
        this.localHost = localHost;
    } else
    {
        throw new IllegalArgumentException("Must be address of a local adapter");
    }
}
 
Example 14
Source File: NetUtils.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Given an InetAddress, checks to see if the address is a local address, by
 * comparing the address with all the interfaces on the node.
 * @param addr address to check if it is local node's address
 * @return true if the address corresponds to the local node
 */
public static boolean isLocalAddress(InetAddress addr) {
  // Check if the address is any local or loop back
  boolean local = addr.isAnyLocalAddress() || addr.isLoopbackAddress();

  // Check if the address is defined on any interface
  if (!local) {
    try {
      local = NetworkInterface.getByInetAddress(addr) != null;
    } catch (SocketException e) {
      local = false;
    }
  }
  return local;
}
 
Example 15
Source File: Helperfunctions.java    From open-rmbt with Apache License 2.0 5 votes vote down vote up
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";
    }
}
 
Example 16
Source File: HTTPSession.java    From mdict-java with GNU General Public License v3.0 5 votes vote down vote up
public HTTPSession(NanoHTTPD httpd, ITempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream, InetAddress inetAddress) {
    this.httpd = httpd;
    this.tempFileManager = tempFileManager;
    this.inputStream = new BufferedInputStream(inputStream, HTTPSession.BUFSIZE);
    this.outputStream = outputStream;
    this.remoteIp = inetAddress.isLoopbackAddress() || inetAddress.isAnyLocalAddress() ? "127.0.0.1" : inetAddress.getHostAddress().toString();
    this.headers = new HashMap<String, String>();
}
 
Example 17
Source File: NanoHTTPD.java    From jmeter-plugins with Apache License 2.0 5 votes vote down vote up
public HTTPSession(TempFileManager tempFileManager,
        InputStream inputStream, OutputStream outputStream,
        InetAddress inetAddress) {
    this.tempFileManager = tempFileManager;
    this.inputStream = new PushbackInputStream(inputStream, BUFSIZE);
    this.outputStream = outputStream;
    String remoteIp = inetAddress.isLoopbackAddress()
            || inetAddress.isAnyLocalAddress() ? "127.0.0.1"
            : inetAddress.getHostAddress();
    headers = new HashMap<>();

    headers.put("remote-addr", remoteIp);
    headers.put("http-client-ip", remoteIp);
}
 
Example 18
Source File: AddressUtils.java    From TorrentEngine with GNU General Public License v3.0 4 votes vote down vote up
/**
 * checks if the provided address is a global-scope ipv6 unicast address
 */
public static boolean isGlobalAddressV6(InetAddress addr) {
	return addr instanceof Inet6Address && !addr.isAnyLocalAddress() && !addr.isLinkLocalAddress() && !addr.isLoopbackAddress() && !addr.isMulticastAddress() && !addr.isSiteLocalAddress() && !((Inet6Address)addr).isIPv4CompatibleAddress();
}
 
Example 19
Source File: UrlTransferUtil.java    From chipster with MIT License 4 votes vote down vote up
public static boolean isLocalhost(String host) throws SocketException, UnknownHostException {
	InetAddress address = InetAddress.getByName(host);
	return address.isAnyLocalAddress() || address.isLoopbackAddress();
}
 
Example 20
Source File: PublicAddressInterfaceCriteria.java    From wildfly-core with GNU Lesser General Public License v2.1 3 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @return <code>address</code> if <code>address</code> is not
 *         {@link InetAddress#isSiteLocalAddress() site-local},
 *         {@link InetAddress#isLinkLocalAddress() link-local}
 *         or a {@link InetAddress#isAnyLocalAddress() wildcard address}.
 */
@Override
protected InetAddress isAcceptable(NetworkInterface networkInterface, InetAddress address) throws SocketException {

    if( !address.isSiteLocalAddress() && !address.isLinkLocalAddress() && !address.isAnyLocalAddress() )
        return address;
    return null;
}