别再纠结!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;
    }

}

参考文献

相关推荐
CodeSheep5 分钟前
中国四大软件外包公司
前端·后端·程序员
一只叫煤球的猫12 小时前
从夯到拉,锐评13个Java Web框架
java·后端·程序员
起风了___14 小时前
Python 批量发邮件脚本:Excel 名单 + Jinja2 模板,带日志与防限流,163 邮箱实测可用
python·程序员
知其然亦知其所以然14 小时前
程序员的最强外挂:用 Spring AI 解锁智谱 AI 画图能力
后端·spring·程序员
q_19132846952 天前
基于SpringBoot2+Vue2的诗词文化传播平台
vue.js·spring boot·mysql·程序员·计算机毕业设计
阿里嘎多学长2 天前
2025-12-16 GitHub 热点项目精选
开发语言·程序员·github·代码托管
Data_Adventure3 天前
为什么不必“活得明白”?
程序员
京东云开发者3 天前
AI Infra平台市场报告:京东云稳居前三
程序员
土豆12503 天前
终端自治时代的 AI 开发范式:Claude Code CLI 全方位实操指南
前端·人工智能·程序员
大模型教程3 天前
14天速成LLM高手!大佬开源学习笔记,GitHub狂揽700星
程序员·llm·agent