2013-07-26 40 views
12

Jak powinienem wykonać konwersję z IPv6 na długi i na odwrót?Konwersja IPv6 na długi i długi na IPv6

Do tej pory mam:

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

    } 

Czy to prawidłowe rozwiązanie lub coś przeoczyłem?

(Idealnie byłoby, gdy roztwór działa zarówno IPv4 jak i IPv6)

Odpowiedz

8

adres IPv6 jest liczbą 128-bitową, jak to opisano here. Długa w Javie jest reprezentowana na 64 bitach, więc potrzebujesz innej struktury, takiej jak BigDecimal lub dwie longy (kontener z tablicą dwóch longów lub po prostu tablica dwóch longów) w celu przechowywania adresu IPv6.

Poniżej jest przykład (tak, aby zapewnić Ci pomysł):

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

}

+0

Ok, zrobię to. A co z konwersją? Czy to jest zrobione dobrze? – Testeross

+0

Łatwo przetestować: wykonaj longToIP (IPToLong ("122.122.122.124")), a otrzymasz "34.34.34.36" zamiast oryginału "122.122.122.124", co oznacza, że ​​coś jest nie tak. –

+0

Masz rację. Czy masz pojęcie, co jest nie tak? – Testeross

6

adres IPv6 nie mogą być przechowywane w długi. Możesz używać BigInteger zamiast długiego.

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; 
} 
10

Można również użyć java.net.InetAddress
Działa zarówno IPv4 i IPv6 (wszystkie formaty)

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

To da ci liczbę ujemną dla górnej połowy zakresu IP. Jeśli chcesz, aby był niepodpisany, musisz przekazać to w signum, aby zachować wartość dodatnią (np. Nowy BigInteger (1, bajty)). – OTrain

+0

@OTrain Dzięki za komentarz. Odpowiedź została zaktualizowana. – Guigoz