java 将IPv6转换为long类型以及将long类型转换为IPv6

wdebmtf2  于 2023-01-24  发布在  Java
关注(0)|答案(4)|浏览(428)

我应该如何执行从IPv6到long的转换,反之亦然?
到目前为止我有:

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);

    }

这是正确的解决方案还是我遗漏了什么?
(It如果该解决方案同时适用于IPv4和IPv6,则将是完美的)

eulz3vhy

eulz3vhy1#

你也可以使用java.net.InetAddress,它支持ipv4和ipv6(所有格式)。
根据OTrains的评论,原始答案已更新为使用无符号整数。

public static BigInteger ipToBigInteger(String addr) throws UnknownHostException {
    InetAddress a = InetAddress.getByName(addr);
    byte[] bytes = a.getAddress();
    return new BigInteger(1, bytes);
}
rsl1atfo

rsl1atfo2#

IPv6地址是一个128位的数字,如here所述,Java中的long表示为64位,因此需要另一种结构,如BigDecimal或two long(包含两个long的数组的容器,或简单地包含两个long的数组)来存储IPv6地址。
下面是一个示例(仅供参考):

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));
    }
}
im9ewurl

im9ewurl3#

IPv6地址不能以long格式存储。可以使用BigInteger代替long格式。

public static BigInteger ipv6ToNumber(String addr) {
    int startIndex=addr.indexOf("::");

    if(startIndex!=-1){

        String firstStr=addr.substring(0,startIndex);
        String secondStr=addr.substring(startIndex+2, addr.length());

        BigInteger first=ipv6ToNumber(firstStr);

        int x=countChar(addr, ':');

        first=first.shiftLeft(16*(7-x)).add(ipv6ToNumber(secondStr));

        return first;
    }

    String[] strArr = addr.split(":");

    BigInteger retValue = BigInteger.valueOf(0);
    for (int i=0;i<strArr.length;i++) {
        BigInteger bi=new BigInteger(strArr[i], 16);
        retValue = retValue.shiftLeft(16).add(bi);
    }
    return retValue;
}

public static String numberToIPv6(BigInteger ipNumber) {
    String ipString ="";
    BigInteger a=new BigInteger("FFFF", 16);

        for (int i=0; i<8; i++) {
            ipString=ipNumber.and(a).toString(16)+":"+ipString;

            ipNumber = ipNumber.shiftRight(16);
        }

    return ipString.substring(0, ipString.length()-1);

}

public static int countChar(String str, char reg){
    char[] ch=str.toCharArray();
    int count=0;
    for(int i=0; i<ch.length; ++i){
        if(ch[i]==reg){
            if(ch[i+1]==reg){
                ++i;
                continue;
            }
            ++count;
        }
    }
    return count;
}
mpbci0fu

mpbci0fu4#

维诺德的答案是正确的,但仍有一些地方需要改进。
首先,在方法“countchar”中,“continue”应替换为“break”。
第二,必须考虑一些边界条件。

public static BigInteger ipv6ToNumber(String addr) {
    int startIndex = addr.indexOf("::");
    if (startIndex != -1) {
        String firstStr = addr.substring(0, startIndex);
        String secondStr = addr.substring(startIndex + 2, addr.length());
        BigInteger first = new BigInteger("0");
        BigInteger second = new BigInteger("0");
        if (!firstStr.equals("")) {
            int x = countChar(addr, ':');
            first = ipv6ToNumber(firstStr).shiftLeft(16 * (7 - x));
        }
        if (!secondStr.equals("")) {
            second = ipv6ToNumber(secondStr);
        }
        first = first.add(second);
        return first;
    }

    String[] strArr = addr.split(":");
    BigInteger retValue = BigInteger.valueOf(0);
    for (int i = 0; i < strArr.length; i++) {
        BigInteger bi = new BigInteger(strArr[i], 16);
        retValue = retValue.shiftLeft(16).add(bi);
    }
    return retValue;
}

public static int countChar(String str, char reg){
    char[] ch=str.toCharArray();
    int count=0;
    for(int i=0; i<ch.length; ++i){
        if(ch[i]==reg){
            if(ch[i+1]==reg){
                ++i;
                break;
            }
            ++count;
        }
    }
    return count;
}

相关问题