将 IPv6 转换为 long 并将 long 转换为 IPv6

时间:2023-04-06
本文介绍了将 IPv6 转换为 long 并将 long 转换为 IPv6的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我应该如何执行从 IPv6 到 long 的转换,反之亦然?

How should I perform conversion from IPv6 to long and vice versa?

到目前为止我有:

    public static long IPToLong(String addr) {
            String[] addrArray = addr.split("\.");
            long num = 0;
            for (int i = 0; i < addrArray.length; i++) {
                    int power = 3 - i;

                    num += ((Integer.parseInt(addrArray[i], 16) % 256 * Math.pow(256, power)));
            }
            return num;
    }

    public static String longToIP(long ip) {
            return ((ip >> 24) & 0xFF) + "."
                    + ((ip >> 16) & 0xFF) + "."
                    + ((ip >> 8) & 0xFF) + "."
                    + (ip & 0xFF);

    }

这是正确的解决方案还是我错过了什么?

Is it correct solution or I missed something?

(如果解决方案对 ipv4 和 ipv6 都有效,那就完美了)

(It would be perfect if the solution worked for both ipv4 and ipv6)

推荐答案

IPv6 地址是一个 128 位数字,如所述 这里.Java 中的 long 以 64 位表示,因此您需要另一种结构,例如 BigDecimal 或两个 long(一个包含两个 long 数组的容器,或者只是一个包含两个 long 数组的容器)来存储 IPv6 地址.

An IPv6 address is a 128-bit number as described here. A long in Java is represented on 64 bits, so you need another structure, like a BigDecimal or two longs (a container with an array of two longs or simply an array of two longs) in order to store an IPv6 address.

下面是一个例子(只是给你一个想法):

Below is an example (just to provide you an idea):

public class Asd {

    public static long[] IPToLong(String addr) {
        String[] addrArray = addr.split(":");//a IPv6 adress is of form 2607:f0d0:1002:0051:0000:0000:0000:0004
        long[] num = new long[addrArray.length];
        
        for (int i=0; i<addrArray.length; i++) {
            num[i] = Long.parseLong(addrArray[i], 16);
        }
        long long1 = num[0];
        for (int i=1;i<4;i++) {
            long1 = (long1<<16) + num[i];
        }
        long long2 = num[4];
        for (int i=5;i<8;i++) {
            long2 = (long2<<16) + num[i];
        }
        
        long[] longs = {long2, long1};
        return longs;
    }
    
    
    public static String longToIP(long[] ip) {
        String ipString = "";
        for (long crtLong : ip) {//for every long: it should be two of them

            for (int i=0; i<4; i++) {//we display in total 4 parts for every long
                ipString = Long.toHexString(crtLong & 0xFFFF) + ":" + ipString;
                crtLong = crtLong >> 16;
            }
        }
        return ipString;
    
    }
    
    static public void main(String[] args) {
        String ipString = "2607:f0d0:1002:0051:0000:0000:0000:0004";
        long[] asd = IPToLong(ipString);
        
        System.out.println(longToIP(asd));
    }
}

这篇关于将 IPv6 转换为 long 并将 long 转换为 IPv6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:将 double 转换为 Int,向下舍入 下一篇:将 32 位无符号整数(大端)转换为 long 并返回

相关文章