Java Code Examples for org.apache.http.conn.util.InetAddressUtils#isIPv4Address()

The following examples show how to use org.apache.http.conn.util.InetAddressUtils#isIPv4Address() . 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 Mizuu with Apache License 2.0 6 votes vote down vote up
/**
 * Get IP address from first non-localhost interface.
 * Taken from http://stackoverflow.com/a/13007325/762442.
 * @param useIPv4  true=return ipv4, false=return ipv6
 * @return  address or empty string
 */
public static String getIPAddress(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 "";
}
 
Example 2
Source File: Utils.java    From BeyondUPnP with Apache License 2.0 6 votes vote down vote up
/**
 * Get IP address from first non-localhost interface
 *
 * @param useIPv4 true=return ipv4, false=return ipv6
 * @return address or empty string
 */
public static String getIPAddress(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 "";
}
 
Example 3
Source File: WifiUtils.java    From FlyWoo with Apache License 2.0 6 votes vote down vote up
public static String getGPRSLocalIPAddress() {
    try {
        Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
        while (en.hasMoreElements()) {
            NetworkInterface nif = en.nextElement();
            Enumeration<InetAddress> enumIpAddr = nif.getInetAddresses();
            while (enumIpAddr.hasMoreElements()) {
                InetAddress mInetAddress = enumIpAddr.nextElement();
                if (!mInetAddress.isLoopbackAddress()
                        && InetAddressUtils.isIPv4Address(mInetAddress.getHostAddress())) {
                    return mInetAddress.getHostAddress();
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 4
Source File: MainActivity.java    From AirFree-Client with GNU General Public License v3.0 6 votes vote down vote up
public String getIPAddress() {
    String ipaddress = "";
    try {
        Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
        while (en.hasMoreElements()) {
            NetworkInterface nif = en.nextElement();
            Enumeration<InetAddress> inet = nif.getInetAddresses();
            while (inet.hasMoreElements()) {
                InetAddress ip = inet.nextElement();
                if (!ip.isLoopbackAddress()
                        && InetAddressUtils.isIPv4Address(ip
                        .getHostAddress())) {
                    return ipaddress = ip.getHostAddress();
                }
            }

        }
    } catch (SocketException e) {
        Log.e("IP & PORT", "获取本地ip地址失败");
        e.printStackTrace();
    }
    return ipaddress;
}
 
Example 5
Source File: RemoteShareActivity.java    From CameraV with GNU General Public License v3.0 6 votes vote down vote up
public static String[] getLocalIpAddresses(){
   try {
	   ArrayList<String> alAddresses = new ArrayList<String>();
	   
       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.isLoopbackAddress()&& InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {
                	alAddresses.add(inetAddress.getHostAddress());
                
                }
           }
       }
       
       return alAddresses.toArray(new String[alAddresses.size()]);
       
       } catch (Exception ex) {
          Log.e("IP Address", ex.toString());
      }
      return null;
}
 
Example 6
Source File: WifiUtils.java    From WifiChat with GNU General Public License v2.0 6 votes vote down vote up
public static String getGPRSLocalIPAddress() {
    try {
        Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
        while (en.hasMoreElements()) {
            NetworkInterface nif = en.nextElement();
            Enumeration<InetAddress> enumIpAddr = nif.getInetAddresses();
            while (enumIpAddr.hasMoreElements()) {
                InetAddress mInetAddress = enumIpAddr.nextElement();
                if (!mInetAddress.isLoopbackAddress()
                        && InetAddressUtils.isIPv4Address(mInetAddress.getHostAddress())) {
                    return mInetAddress.getHostAddress();
                }
            }
        }
    }
    catch (SocketException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 7
Source File: HostHeaderHandler.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if the provided address is an IPv6 address (or could be interpreted as one). This method is more
 * lenient than {@link InetAddressUtils#isIPv6Address(String)} because of different interpretations of IPv4-mapped
 * IPv6 addresses.
 *
 * See RFC 5952 Section 4 for more information on textual representation of the IPv6 addresses.
 *
 * @param address the address in text form
 * @return true if the address is or could be parsed as an IPv6 address
 */
static boolean isIPv6Address(String address) {
    // Note: InetAddressUtils#isIPv4MappedIPv64Address() fails on addresses that do not compress the leading 0:0:0... to ::
    // Expanded for debugging purposes
    boolean isNormalIPv6 = InetAddressUtils.isIPv6Address(address);

    // If the last two hextets are written in IPv4 form, treat it as an IPv6 address as well
    String everythingAfterLastColon = StringUtils.substringAfterLast(address, ":");
    boolean isIPv4 = InetAddressUtils.isIPv4Address(everythingAfterLastColon);
    boolean isIPv4Mapped = InetAddressUtils.isIPv4MappedIPv64Address(everythingAfterLastColon);
    boolean isCompressable = address.contains("0:0") && !address.contains("::");

    return isNormalIPv6 || isIPv4;
}
 
Example 8
Source File: WebTools.java    From zrlog with Apache License 2.0 5 votes vote down vote up
/**
 * 处理由于浏览器使用透明代理,或者是WebServer运行在诸如 nginx/apache 这类 HttpServer后面的情况,通过获取请求头真实IP地址
 *
 * @param request
 * @return
 */
public static String getRealIp(HttpServletRequest request) {
    String ip = null;
    //bae env
    if (ZrLogUtil.isBae() && request.getHeader("clientip") != null) {
        ip = request.getHeader("clientip");
    }
    if (ip == null || ip.length() == 0) {
        ip = request.getHeader("X-forwarded-for");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("X-Real-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getRemoteAddr();
    }
    if (InetAddressUtils.isIPv4Address(ip) || InetAddressUtils.isIPv6Address(ip)) {
        return ip;
    }
    throw new IllegalArgumentException(ip + " not ipAddress");
}
 
Example 9
Source File: StreamCameraActivity.java    From peepers with Apache License 2.0 5 votes vote down vote up
private static String tryGetIpV4Address()
{
    try
    {
        final Enumeration<NetworkInterface> en =
                NetworkInterface.getNetworkInterfaces();
        while (en.hasMoreElements())
        {
            final NetworkInterface intf = en.nextElement();
            final Enumeration<InetAddress> enumIpAddr =
                    intf.getInetAddresses();
            while (enumIpAddr.hasMoreElements())
            {
                final  InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress())
                {
                    final String addr = inetAddress.getHostAddress().toUpperCase();
                    if (InetAddressUtils.isIPv4Address(addr))
                    {
                        return addr;
                    }
                } // if
            } // while
        } // for
    } // try
    catch (final Exception e)
    {
        // Ignore
    } // catch
    return null;
}
 
Example 10
Source File: LFXNetworkUtils.java    From lifx-sdk-android with MIT License 5 votes vote down vote up
@SuppressLint("DefaultLocale")
public static String getLocalHostAddress() {
    boolean useIPv4 = true;

    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 "";
}
 
Example 11
Source File: Utilities.java    From balanced-android with MIT License 5 votes vote down vote up
/**
 * Get IP address from first non-localhost interface
 *
 * @param useIPv4 true=return ipv4 address, false=return ipv6 address
 * @return address or empty string
 */
protected static String getIPAddress(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) {} // ignore exceptions

   return "";
}
 
Example 12
Source File: ConnectionConfiguration.java    From AndroidPNClient with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the host to use when establishing the connection. The host and port to use
 * might have been resolved by a DNS lookup as specified by the XMPP spec (and therefore
 * may not match the {@link #getServiceName service name}.
 *
 * @return the host to use when establishing the connection.
 */
public String getHost() {
    // 如果不是IP,则尝试将它以域名进行IP转换。
    if(!InetAddressUtils.isIPv4Address(host) && !InetAddressUtils.isIPv6Address(host)) {
        try {
            InetAddress address = InetAddress.getByName(host);
            host =  address.getHostAddress();
            Log.d(LOG_TAG, "transform host name to host address:"+host);
        } catch (UnknownHostException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
        }
    }
    return host;
}
 
Example 13
Source File: RequestEntityRestStorageService.java    From cyberduck with GNU General Public License v3.0 4 votes vote down vote up
private static Jets3tProperties toProperties(final Host bookmark, final S3Protocol.AuthenticationHeaderSignatureVersion signatureVersion) {
    final Jets3tProperties properties = new Jets3tProperties();
    final Preferences preferences = PreferencesFactory.get();
    if(log.isDebugEnabled()) {
        log.debug(String.format("Configure for endpoint %s", bookmark));
    }
    // Use default endpoint for region lookup
    if(bookmark.getHostname().endsWith(preferences.getProperty("s3.hostname.default"))) {
        // Only for AWS
        properties.setProperty("s3service.s3-endpoint", preferences.getProperty("s3.hostname.default"));
        properties.setProperty("s3service.disable-dns-buckets",
            String.valueOf(preferences.getBoolean("s3.bucket.virtualhost.disable")));
    }
    else {
        properties.setProperty("s3service.s3-endpoint", bookmark.getHostname());
        if(InetAddressUtils.isIPv4Address(bookmark.getHostname()) || InetAddressUtils.isIPv6Address(bookmark.getHostname())) {
            properties.setProperty("s3service.disable-dns-buckets", String.valueOf(true));
        }
        else {
            properties.setProperty("s3service.disable-dns-buckets",
                String.valueOf(preferences.getBoolean("s3.bucket.virtualhost.disable")));
        }
    }
    properties.setProperty("s3service.enable-storage-classes", String.valueOf(true));
    if(StringUtils.isNotBlank(bookmark.getProtocol().getContext())) {
        if(!Scheme.isURL(bookmark.getProtocol().getContext())) {
            properties.setProperty("s3service.s3-endpoint-virtual-path",
                PathNormalizer.normalize(bookmark.getProtocol().getContext()));
        }
    }
    properties.setProperty("s3service.https-only", String.valueOf(bookmark.getProtocol().isSecure()));
    if(bookmark.getProtocol().isSecure()) {
        properties.setProperty("s3service.s3-endpoint-https-port", String.valueOf(bookmark.getPort()));
    }
    else {
        properties.setProperty("s3service.s3-endpoint-http-port", String.valueOf(bookmark.getPort()));
    }
    // The maximum number of retries that will be attempted when an S3 connection fails
    // with an InternalServer error. To disable retries of InternalError failures, set this to 0.
    properties.setProperty("s3service.internal-error-retry-max", String.valueOf(0));
    // The maximum number of concurrent communication threads that will be started by
    // the multi-threaded service for upload and download operations.
    properties.setProperty("s3service.max-thread-count", String.valueOf(1));
    properties.setProperty("httpclient.proxy-autodetect", String.valueOf(false));
    properties.setProperty("httpclient.retry-max", String.valueOf(0));
    properties.setProperty("storage-service.internal-error-retry-max", String.valueOf(0));
    properties.setProperty("storage-service.request-signature-version", signatureVersion.toString());
    properties.setProperty("storage-service.disable-live-md5", String.valueOf(true));
    properties.setProperty("storage-service.default-region", bookmark.getRegion());
    return properties;
}
 
Example 14
Source File: NetworkAddressValidator.java    From tajo with Apache License 2.0 4 votes vote down vote up
@Override
protected <T> boolean validateInternal(T object) {
  boolean result = false;
  
  if (object != null) {
    if (object instanceof CharSequence) {
      String valueString = object.toString();
      if (valueString.isEmpty()) {
        result = true;
      } else {
        int separatorIdx = valueString.indexOf(':');
        String hostOrIpAddress = null;
        
        if (separatorIdx > -1) {
          if (valueString.indexOf(':', separatorIdx+1) > -1) {
            // it is IPV6 representation.
            int leftBracketsIdx = valueString.indexOf('[');
            int rightBracketsIdx = valueString.indexOf(']');
            int periodIdx = valueString.indexOf('.');
            
            if ((leftBracketsIdx > -1) && (rightBracketsIdx > -1) && 
                (valueString.length() > (rightBracketsIdx+1)) &&
                valueString.charAt(rightBracketsIdx+1) == ':') {
              hostOrIpAddress = valueString.substring(leftBracketsIdx+1, rightBracketsIdx);
              separatorIdx = rightBracketsIdx+1;
            } else if ((periodIdx > -1)) {
              hostOrIpAddress = valueString.substring(0, periodIdx);
              separatorIdx = periodIdx;
            } else {
              separatorIdx = valueString.lastIndexOf(':');
              hostOrIpAddress = valueString.substring(0, separatorIdx);
            }
          } else {            
            hostOrIpAddress = valueString.substring(0, separatorIdx);
          }
        } else {
          hostOrIpAddress = valueString;
        }
        
        result = ((hostnamePattern.matcher(hostOrIpAddress).find()) | 
            InetAddressUtils.isIPv4Address(hostOrIpAddress) |
            InetAddressUtils.isIPv6Address(hostOrIpAddress));
        
        if (separatorIdx > -1) {
          result &= portNumberPattern.matcher(valueString.substring(separatorIdx + 1)).find();
        }
      }
    }
  } else {
    result = true;
  }
  
  return result;
}
 
Example 15
Source File: AbstractCommonHostnameVerifierDef.java    From steady with Apache License 2.0 4 votes vote down vote up
private static boolean isIPAddress(final String hostname) {
    return hostname != null &&
        (InetAddressUtils.isIPv4Address(hostname) ||
                InetAddressUtils.isIPv6Address(hostname));
}
 
Example 16
Source File: AbstractVerifierFix.java    From steady with Apache License 2.0 4 votes vote down vote up
private static boolean isIPAddress(final String hostname) {
    return hostname != null &&
        (InetAddressUtils.isIPv4Address(hostname) ||
                InetAddressUtils.isIPv6Address(hostname));
}
 
Example 17
Source File: AbstractCommonHostnameVerifierFix.java    From steady with Apache License 2.0 4 votes vote down vote up
private static boolean isIPAddress(final String hostname) {
    return hostname != null &&
        (InetAddressUtils.isIPv4Address(hostname) ||
                InetAddressUtils.isIPv6Address(hostname));
}
 
Example 18
Source File: J_AbstractVerifier_V.java    From steady with Apache License 2.0 4 votes vote down vote up
private static boolean isIPAddress(final String hostname) {
    return hostname != null &&
        (InetAddressUtils.isIPv4Address(hostname) ||
                InetAddressUtils.isIPv6Address(hostname));
}
 
Example 19
Source File: PrivacyEnforcementService.java    From prebid-server-java with Apache License 2.0 4 votes vote down vote up
/**
 * Masks ip v4 address by replacing last group with zero.
 */
private static String maskIpv4(String ip) {
    return ip != null && InetAddressUtils.isIPv4Address(ip) ? maskIp(ip, ".", 1) : ip;
}
 
Example 20
Source File: HWUtils.java    From RePlugin-GameSdk with Apache License 2.0 3 votes vote down vote up
/**
 * 获取当前Ip地址
 * 
 * @return
 */
public static String getCurrentIp(Activity context) {

	try {

		String ipv4;

		List nilist = Collections.list(NetworkInterface
				.getNetworkInterfaces());
		for (Object object : nilist) {
			NetworkInterface ni = (NetworkInterface) object;

			List ialist = Collections.list(ni.getInetAddresses());

			for (Object obj : ialist) {

				InetAddress address = (InetAddress) obj;

				if (!address.isLoopbackAddress()
						&& InetAddressUtils.isIPv4Address(ipv4 = address
								.getHostAddress())) {

					return ipv4;

				}

			}

		}

	} catch (SocketException ex) {

	}

	return null;
}