下面列出了怎么用org.apache.http.conn.util.InetAddressUtils的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 获取设备IP地址
*
* @return 设备ip地址
*/
public static String getLocalIpAddress(){
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.isLoopbackAddress() && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {
return inetAddress.getHostAddress().toString();
}
}
}
}catch (SocketException e) {
// TODO: handle exception
Log.v("Steel", "WifiPreference IpAddress---error-" + e.toString());
}
return null;
}
public String GetIp(Boolean isV4) {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> ipAddr = intf.getInetAddresses(); ipAddr.hasMoreElements(); ) {
InetAddress inetAddress = ipAddr.nextElement();
if(isV4) {
// ipv4地址
if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {
return inetAddress.getHostAddress();
}
}else{
// ipv6地址
if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv6Address(inetAddress.getHostAddress())) {
return inetAddress.getHostAddress();
}
}
}
}
} catch (Exception ex) {
//
}
return "";
}
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 ip.getHostAddress();
}
}
}
} catch (SocketException e) {
Log.e("IP & PORT", "获取本地ip地址失败");
e.printStackTrace();
}
return ipaddress;
}
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;
}
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;
}
/**
* 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 "";
}
public static String getIPAddress(boolean useIPv4) throws SocketException {
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) {
if (sAddr.startsWith("fe80") || sAddr.startsWith("FE80")) // skipping link-local addresses
continue;
int delim = sAddr.indexOf('%'); // drop ip6 port suffix
return delim<0 ? sAddr : sAddr.substring(0, delim);
}
}
}
}
}
return "";
}
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;
}
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;
}
/**
* 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 "";
}
private String normaliseIPv6Address(final String hostname) {
if (hostname == null || !InetAddressUtils.isIPv6Address(hostname)) {
return hostname;
}
try {
final InetAddress inetAddress = InetAddress.getByName(hostname);
return inetAddress.getHostAddress();
} catch (final UnknownHostException uhe) { // Should not happen, because we check for IPv6 address above
log.error("Unexpected error converting "+hostname, uhe);
return hostname;
}
}
private String normaliseIPv6Address(final String hostname) {
if (hostname == null || !InetAddressUtils.isIPv6Address(hostname)) {
return hostname;
}
try {
final InetAddress inetAddress = InetAddress.getByName(hostname);
return inetAddress.getHostAddress();
} catch (final UnknownHostException uhe) { // Should not happen, because we check for IPv6 address above
log.error("Unexpected error converting "+hostname, uhe);
return hostname;
}
}
private String normaliseIPv6Address(final String hostname) {
if (hostname == null || !InetAddressUtils.isIPv6Address(hostname)) {
return hostname;
}
try {
final InetAddress inetAddress = InetAddress.getByName(hostname);
return inetAddress.getHostAddress();
} catch (final UnknownHostException uhe) { // Should not happen, because we check for IPv6 address above
log.error("Unexpected error converting "+hostname, uhe);
return hostname;
}
}
private String normaliseIPv6Address(final String hostname) {
if (hostname == null || !InetAddressUtils.isIPv6Address(hostname)) {
return hostname;
}
try {
final InetAddress inetAddress = InetAddress.getByName(hostname);
return inetAddress.getHostAddress();
} catch (final UnknownHostException uhe) { // Should not happen, because we check for IPv6 address above
log.error("Unexpected error converting "+hostname, uhe);
return hostname;
}
}
private String normaliseIPv6Address(final String hostname) {
if (hostname == null || !InetAddressUtils.isIPv6Address(hostname)) {
return hostname;
}
try {
final InetAddress inetAddress = InetAddress.getByName(hostname);
return inetAddress.getHostAddress();
} catch (final UnknownHostException uhe) { // Should not happen, because we check for IPv6 address above
log.error("Unexpected error converting "+hostname, uhe);
return hostname;
}
}
private String normaliseIPv6Address(final String hostname) {
if (hostname == null || !InetAddressUtils.isIPv6Address(hostname)) {
return hostname;
}
try {
final InetAddress inetAddress = InetAddress.getByName(hostname);
return inetAddress.getHostAddress();
} catch (final UnknownHostException uhe) { // Should not happen, because we check for IPv6 address above
log.error("Unexpected error converting "+hostname, uhe);
return hostname;
}
}
public static boolean validContainer(String container) throws InvalidContainerNameException {
if (container != null && container.length() < 4) {
throw new InvalidContainerNameException("Container " + container
+ " length must be at least 3 letters");
}
if (InetAddressUtils.isIPv4Address(container)) {
throw new InvalidContainerNameException("Container " + container
+ " is of IP address pattern");
}
return true;
}
private String checkIpAddress(String ipAddress, boolean checkForLocalhost) {
Enumeration<NetworkInterface> ifs = null;
try {
ifs = NetworkInterface.getNetworkInterfaces();
} catch(SocketException e) {
log.error("checkIpAddress cannot get ip address of this host, Exiting with message: " + e.getMessage(), e);
return null;
}
String addressString = null;
InetAddress address = null;
while (ifs.hasMoreElements() && addressString == null) {
NetworkInterface xface = ifs.nextElement();
Enumeration<InetAddress> addrs = xface.getInetAddresses();
String name = xface.getName();
int IPsPerNic = 0;
while (addrs.hasMoreElements() && IPsPerNic == 0) {
address = addrs.nextElement();
if (InetAddressUtils.isIPv4Address(address.getHostAddress())) {
log.debug(name + " ... has IPV4 addr " + address);
if(checkForLocalhost && (!name.equalsIgnoreCase(Configuration.LOOP_BACK_INTERFACE) || !address.getHostAddress().equalsIgnoreCase(Configuration.LOOP_BACK_ADDRESS))) {
IPsPerNic++;
addressString = address.getHostAddress();
log.debug("checkIpAddress found " + addressString + " from interface " + name);
}
else if(ipAddress != null && ipAddress.equalsIgnoreCase(address.getHostAddress())){
addressString = ipAddress;
IPsPerNic++;
}
}
}
}
return addressString;
}
/**
* Checks if the given id is a valid IP address
*
* @param id ip to be checked.
*/
private boolean isIPAddress(String id) {
return InetAddressUtils.isIPv4Address(id) ||
InetAddressUtils.isIPv4MappedIPv64Address(id) ||
InetAddressUtils.isIPv6Address(id) ||
InetAddressUtils.isIPv6HexCompressedAddress(id) ||
InetAddressUtils.isIPv6StdAddress(id);
}
/**
* 处理由于浏览器使用透明代理,或者是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");
}
/**
* 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;
}
@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 "";
}
/**
* 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;
}
/**
* Get IP address from first non-localhost interface
*
* @param ipv4 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 e) {
e.printStackTrace();
}
return "";
}
/**
* 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 "";
}
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;
}
/**
* 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;
}
/**
* Masks ip v6 address by replacing last number of groups .
*/
private static String maskIpv6(String ip, Integer groupsNumber) {
return ip != null && InetAddressUtils.isIPv6Address(ip) ? maskIp(ip, ":", groupsNumber) : ip;
}
private static boolean isIPAddress(final String hostname) {
return hostname != null &&
(InetAddressUtils.isIPv4Address(hostname) ||
InetAddressUtils.isIPv6Address(hostname));
}
private static boolean isIPAddress(final String hostname) {
return hostname != null &&
(InetAddressUtils.isIPv4Address(hostname) ||
InetAddressUtils.isIPv6Address(hostname));
}