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

}

参考文献

相关推荐
SoleMotive.3 小时前
一个准程序员的健身日志:用算法调试我的增肌计划
python·程序员·健身·职业转型
万岳科技程序员小金6 小时前
多商户商城系统源码 + APP/小程序开发:技术架构与应用解
程序员·开源·源码·多商户商城系统源码·多商户商城小程序·多商户商城app开发·多商户商城平台开发
NAGNIP9 小时前
程序员效率翻倍的快捷键大全!
前端·后端·程序员
阿里嘎多学长11 小时前
2026-02-03 GitHub 热点项目精选
开发语言·程序员·github·代码托管
修己xj18 小时前
山野的风,城市的窗:一位拾粪爷爷与我的时代之问
程序员
沈二到不行18 小时前
【22-26】蜉蝣一日、入樊笼尔
程序员·ai编程·全栈
AI绘画哇哒哒20 小时前
【干货收藏】深度解析AI Agent框架:设计原理+主流选型+项目实操,一站式学习指南
人工智能·学习·ai·程序员·大模型·产品经理·转行
程序员鱼皮2 天前
刚刚,Claude Opus 4.6 和 GPT-5.3-Codex 同时炸场!AI 编程要变天了
计算机·ai·程序员·互联网·软件开发
Stephen_Young3 天前
32岁程序员猝死:让我想起了我曾经的加班经历,庆幸自己还活着
程序员·工控
良许Linux3 天前
51单片机都有哪些优缺点
单片机·程序员·嵌入式·编程