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

}

参考文献

相关推荐
京东云开发者15 小时前
研发排查问题的利器:一款方法调用栈跟踪工具
程序员
京东云开发者15 小时前
JDD Oxygen智能零售论坛 | 《大模型时代的广告营销变革与实践》
程序员
京东云开发者15 小时前
常用Web 实时通信技术:原理+选型,一篇通关
程序员
技术爬爬虾18 小时前
AI编程新王Codex详细攻略,一期视频精通,附免费使用方法
程序员·github
大模型教程20 小时前
开源RAG神器RAGFlow深度解析:融合Agent能力,零门槛搭建企业级AI知识库
程序员·llm·agent
AI大模型20 小时前
斩获72k Star!谷歌云AI大牛开源LLM应用案例库,拿来即用
程序员·llm·agent
AI大模型20 小时前
GitHub斩获 19.9k 星!免费!从零开始系统学习大语言模型
程序员·llm·agent
大模型教程21 小时前
后悔没早点读!Sebastian Raschka 新书《从头开始推理》
程序员·llm·agent
SimonKing1 天前
【开发者必备】Spring Boot 2.7.x:WebMvcConfigurer配置手册来了(四)!
java·后端·程序员
前端开发张小七2 天前
写个刚步入大学生活的弟弟的一封信
程序员