IPv4 Host Address

IPv4 Host Address

IPv4 utility:

package com.jiax3.common.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/* This utility provides methods to either convert an IPv4 address to its long format or a 32bit dotted format.
*
* @author Michael
* Created on 2013.09.29
*/
public class IPv4 {

private static Logger logger = LoggerFactory.getLogger(IPv4.class);
private static String hostAddress;

static {
hostAddress = getHostAddress();
}

/**
* Returns the long format of the provided IP address.
*
* @param ipAddress
* the IP address
* @return the long format of ipAddress
* @throws IllegalArgumentException
* if ipAddress is invalid
*/
public static long toLong(String ipAddress) {
if (ipAddress == null || ipAddress.isEmpty()) {
throw new IllegalArgumentException(
“ip address cannot be null or empty”);
}
String[] octets = ipAddress.split( java.util.regex.Pattern.quote(“.”));
if (octets.length != 4) {
throw new IllegalArgumentException(“invalid ip address”);
}
long ip = 0;
for (int i = 3; i >= 0; i–) {
long octet = Long.parseLong(octets[3 – i]);
if (octet > 255 || octet throw new IllegalArgumentException(“invalid ip address”);
}
ip |= octet }
return ip;
}

/**
* Returns the 32bit dotted format of the provided long ip.
*
* @param ip
* the long ip
* @return the 32bit dotted format of ip
* @throws IllegalArgumentException
* if ip is invalid
*/
public static String toString(long ip) {
// if ip is bigger than 255.255.255.255 or smaller than 0.0.0.0
if (ip > 4294967295l || ip throw new IllegalArgumentException(“invalid ip”);
}
StringBuilder ipAddress = new StringBuilder();
for (int i = 3; i >= 0; i–) {
int shift = i * 8;
ipAddress.append((ip & (0xff > shift);
if (i > 0) {
ipAddress.append(“.”);
}
}
return ipAddress.toString();
}

/**
* 获取主机ip
* @return
* @throws SocketException
*/
public static String getHostAddress() {
try {
Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface nif = netInterfaces.nextElement();
Enumeration iparray = nif.getInetAddresses();
while (iparray.hasMoreElements()) {
InetAddress ip = (InetAddress) iparray.nextElement();
if (ip != null && ip instanceof Inet4Address && !ip.getHostAddress().equals(“127.0.0.1”)){
return ip.getHostAddress();
}
}
}
} catch (Exception e) {
logger.error(“IPv4 static method getHostAddress error: {}”, e);
}
return null;
}

/**
* 获取缓存静态主机ip
* @return
*/
public static String getCacheHostAddress() {
return hostAddress;
}

}

-end-

好烂啊有点差凑合看看还不错很精彩 (No Ratings Yet)
Loading...
188 views

3 thoughts on “IPv4 Host Address

  1. Thanks for the auspicious writeup. It actually was once a leisure account it. Glance complex to far added agreeable from you! By the way, how can we keep up a correspondence?

发表评论

电子邮件地址不会被公开。 必填项已用*标注

跳至工具栏