java写个util,获取本机ip,并使用Google Guava 缓存起来
四个方法:
- 获取本机ipv4
- ip转16进制
- 16进制转ip
- 校验ip
首先,Google Guava使用的maven配置
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.6.1.8</version>
</dependency>
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
public class MyUtil {
//使用缓存
private static Cache<String, String> cache = CacheBuilder
.newBuilder()
.maximumSize(1)
.expireAfterWrite(2, TimeUnit.DAYS)
.build();
/**
* 获取本机ipv4地址, 当机器有多张网卡时,只会获取其中一个
* 默认会缓存2天
*/
public static String getIpv4() throws Exception {
return cache.get("ip", new Callable<String>() {
@Override
public String call() throws Exception {
Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
while (nis.hasMoreElements()) {
NetworkInterface ni = nis.nextElement();
if (!ni.isUp() || ni.isLoopback() || ni.isVirtual()) {
continue;
}
Enumeration<InetAddress> ias = ni.getInetAddresses();
if (!ias.hasMoreElements()) {
continue;
}
while (ias.hasMoreElements()) {
InetAddress ia = ias.nextElement();
if (ia.isLoopbackAddress()) {
continue;
}
if (!(ia instanceof Inet4Address)) {
continue;
}
return ia.getHostAddress();
}
}
return "";
}
});
}
/**
* 判断是否是合法的ipv4地址
* @param ipStr
* @return
*/
public static boolean isIpV4(String ipStr){
if (ipStr != null && !ipStr.isEmpty()) {
String regex="^(((\\d{1,2})|(1\\d{2})|(2[0-4]\\d)|(25[0-5]))\\.){3}((\\d{1,2})|(1\\d{2})|(2[0-4]\\d)|(25[0-5]))$";
if (ipStr.matches(regex)) {
return true;
} else {
return false;
}
}
return false;
}
/**
* 将ip转换为定长8个字符的16进制表示形式:255.255.255.255 -> FFFFFFFF
* @param ip ipv4地址
* @return String hex表示的ipv4地址
*/
public static String hexIp(String ip) {
StringBuilder sb = new StringBuilder();
for (String seg : ip.split(IP_SPLIT)) {
String h = Integer.toHexString(Integer.parseInt(seg));
if (h.length() == 1) {
sb.append("0");
}
sb.append(h);
}
return sb.toString();
}
/**
* 将16进制表示的ip地址转换为数字表示形式: FFFFFFFF -> 255.255.255.255
* @param hexIp hex表示的ipv4地址
* @return String 数字表示ipv4地址
*/
public static String hexIpToString(String hexIp){
StringBuilder sb = new StringBuilder();
int i = 0;
StringBuffer tmp = new StringBuffer();
int len = hexIp.toCharArray().length;
for (char seg : hexIp.toCharArray()) {
tmp.append(seg);
i++;
if(i % 2 == 0){
int val = Integer.parseInt(tmp.toString(), 16);
sb.append(val);
if(i < len){
sb.append(".");
}
tmp = new StringBuffer();
}
}
return sb.toString();
}
public static void main(String[] args) throws Exception {
//测试
String ipv4 = getIpv4();
System.out.println("ip:"+ipv4);
String s16 = hexIp(ipv4);
System.out.println("16进制ip:"+s16);
String s10 = hexIpToString(s16);
System.out.println("10进制ip:"+s10);
boolean isOk = isIpV4(ipv4);
System.out.println("是否是有效ip:"+isOk );
}
}
本文介绍了一个Java实用工具类,用于获取本机IPv4地址,并利用Google Guava库进行缓存优化。该工具类包含IP地址的十六进制转换、反转换及有效性验证功能。
2万+

被折叠的 条评论
为什么被折叠?



