ip地址转换int保存占用空间更小
个人理解
转换后在数据库里可读性差,需要用一定的算法进行转换后可读,对于空间要求不高的,可以不转换,但是要知道可以转,会转
package test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* IPv4地址和int互换
*/
public class Utils{
public static void main(String[] args) {
String ip = "127.0.0.1";
int ipint = ip2Int(ip);
System.out.println(ipint);
System.out.println(int2Ip(ipint));
}
/**
* IPv4地址转换为int类型数字
*
* @param ipv4Addr
* @return
*/
public static int ip2Int(String ip) {
// 判断是否是ip格式的
if (!isIp(ipv4Addr))
throw new RuntimeException("Invalid ip address");
// 匹配数字
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(ipv4Addr);
int result = 0;
int counter = 0;
while (matcher.find()) {
int value = Integer.parseInt(matcher.group());
result = (value << 8 * (3 - counter++)) | result;
}
return result;
}
/**
* 是否为IPV4正则
*/
private static boolean isIp(String ip) {
String regex = "(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])"; // 0-255的数字
String regex = regex + "(\\." + lower + "){3}";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(ip);
return matcher.matches();
}
/**
* int转ip
*/
public static String int2Ip(int ip) {
StringBuilder sb = new StringBuilder();
int num = 0;
boolean needPoint = false; // 是否需要加入'.'
for (int i = 0; i < 4; i++) {
if (needPoint) {
sb.append('.');
}
needPoint = true;
int offset = 8 * (3 - i);
num = (ip >> offset) & 0xff;
sb.append(num);
}
return sb.toString();
}
}
来自这个大神 https://www.jb51.net/article/195619.htm
日常记录
互相交流
欢迎指教
各显神通