MySQL 有这么两个函数可以直接使用: INET_ATON() 将IP转为十进制数字 INET_NTOA() 将数字转换为IP
Java 转换方法
public static Long getIPNum(final String IP) {
Long IPNum = 0L;
final String IPStr = IP.trim();
if (IP != null && IPStr.length() != 0) {
final String[] subips = IPStr.split("\\.");
for (final String str : subips) {
IPNum = IPNum << 8;
IPNum += Integer.parseInt(str);
}
}
return IPNum;
}
public static String getIPString(final Long IPNum) {
final Long[] andNumbers = {0xff000000L, 0x00ff0000L, 0x0000ff00L, 0x000000ffL};
final StringBuilder IPStrSb = new StringBuilder();
for (int i = 0; i < 4; i++) {
IPStrSb.append(String.valueOf((IPNum & andNumbers[i]) >> 8 * (3 - i)));
if (i != 3) {
IPStrSb.append(".");
}
}
return IPStrSb.toString();
}
评论区