别再纠结!IP 存储类型选择攻略来袭

ip存储

ipv4

ipv4使用long类型进行存储即可

java 复制代码
public static long ipToLong(String ipString) throws NumberFormatException {
    long result = 0;
    String[] terms = ipString.split("\\.");
    if (terms.length != 4) {
        return -1;
    }
    result += Long.parseLong(terms[0]) << 24;
    result += Long.parseLong(terms[1]) << 16;
    result += Long.parseLong(terms[2]) << 8;
    result += Long.parseLong(terms[3]);
    return result;
}

public static String longToIp(long ipLong) {
    return (ipLong >>> 24) + "." +
            ((ipLong >>> 16) & 0xFF) + "." +
            ((ipLong >>> 8) & 0xFF) + "." +
            (ipLong & 0xFF);
}

public static void main(String[] args) {
        long result = ipToLong("255.255.255.255");
        System.out.println(result);
        System.out.println(longToIp(result));
}

ipv6

ipv6使用long类型是存储不了的,需要使用BigInteger

java 复制代码
public static BigInteger ip6ToNumber(String ipv6Address) throws NumberFormatException {
    try{
        InetAddress inetAddress = InetAddress.getByName(ipv6Address);
        String hostAddress = inetAddress.getHostAddress();

        StringBuilder decimalString = new StringBuilder();
        String[] split = hostAddress.split(":");
        for(String s : split){
            // 十六进制转为十进制
            int i = Integer.parseInt(s, 16);
            // 不足五位拿0补齐
            decimalString.append(String.format("%05d",i));
        }

        return new BigInteger(decimalString.toString());
    } catch (UnknownHostException exception){
        LOGGER.error("ipv6转换失败 {}", ipv6Address, exception);
        return BigInteger.ZERO;
    }

}

参考文献

相关推荐
你的人类朋友1 分钟前
什么是OpenSSL
后端·安全·程序员
文心快码BaiduComate4 小时前
文心快码入选2025服贸会“数智影响力”先锋案例
前端·后端·程序员
集成显卡4 小时前
windows 下使用 bat 批处理运行 Chrome 无头模式刷一波访问量
windows·程序员
大模型教程6 小时前
小白学大模型:降低幻觉的六种方法
程序员·llm·agent
AI大模型6 小时前
小白学大模型:适合1B模型的17个提示词
程序员·llm·agent
SimonKing13 小时前
一键开启!Spring Boot 的这些「魔法开关」@Enable*,你用对了吗?
java·后端·程序员
redreamSo14 小时前
找对象这件事,选择永远比努力重要:建立婚恋权重模型,选择高效渠道,精准识人与主动推进,我不信这还不行?
程序员
AI大模型1 天前
GitHub 狂飙 72k Star,这本大模型书凭啥能圈粉无数?
程序员·llm·agent
大模型教程1 天前
小白学大模型:从零搭建LLaMA
程序员·llm·llama