别再纠结!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 小时前
解析 OpenClaw AgentSkills:AI Agent 如何通过「技能包」实现专业化
人工智能·程序员·代码规范
起风了___19 小时前
解决大数据渲染卡顿:Vue3 虚拟列表组件的完整实现方案
前端·程序员
程序员鱼皮21 小时前
315 曝光的 GEO 投毒是什么?教你 8 招,让 AI 主动推荐你!
ai·程序员·编程·ai编程·seo
壹方秘境2 天前
厌倦了那些看着像一个模版复刻出来的抓包工具,我开发了一款iOS端HTTPS抓包调试工具
ios·程序员·产品
dleei2 天前
彻底淘汰老旧 SVG 插件:unplugin-icons 与 Tailwind CSS v4 自定义图标最佳实践
前端·程序员·前端框架
前端小张同学2 天前
有了AI大家的日常是轻松了还是更焦虑了呢?
人工智能·程序员·ai编程
编码忘我2 天前
JVM 运行时数据区详解
java·后端·程序员
Flutter笔记2 天前
我做了一个鼾声记录App,聊聊背后的功能设计
程序员·产品·全栈
PFinal社区_南丞2 天前
2026 Agent 生态爆发:这 5 个项目值得 All in
人工智能·程序员