简体   繁体   中英

How to convert IPv6 Addresses to and from BigInteger in Scala

Looking to convert IPv6 Strings (such as 2001:0:4137:9e76:34b7:2e31:3f57:fd9a) to BigInteger and from BigInteger to IPv6 Strings.

import java.math.BigInteger
import java.net.InetAddress
import java.net.Inet6Address
def ipv6ToBigInteger(ipv6 : String) : BigInteger = {
    val ia = InetAddress.getByName(ipv6)
    val byteArr : Array[Byte] = ia.getAddress()
    var ipNumber = new BigInteger("0")
    if (ia.isInstanceOf[Inet6Address]) {
        ipNumber = new BigInteger(1, byteArr)
    }
    return ipNumber
}

def bigIntegerToIPv6(ipv6Num : BigInteger) : String = {
    val ipv6Str = InetAddress.getByAddress(ipv6Num.toByteArray).toString()
    return ipv6Str.replaceFirst("/", "")
}

val ipv6 = "2001:0:4137:9e76:34b7:2e31:3f57:fd9a"
val ipv6Num = ipv6ToBigInteger(ipv6) // ipv6Num: java.math.BigInteger = 42540488182159607633435240198452018586
val ipv6Str = bigIntegerToIPv6(ipv6Num) // ipv6Str: String = 2001:0:4137:9e76:34b7:2e31:3f57:fd9a
ipv6 == ipv6Str // res0: Boolean = true

UPDATE EDIT:

Per a suggested edit from an anonymous user:

"Comment: InetAddress.getByAddress requires a 16-byte array in order to parse an IPv6 address (4-byte array for IPv4). As it was, the code failed for any value that did not result in a 16-byte array when.toByteArray was called on it"

def bigIntToFixedSizeByteArray(n: BigInteger, size: Int = 16): Array[Byte] = {
    val a = n.toByteArray
    val leadingLength = math.max(size - a.length, 0)
    Array.ofDim[Byte](leadingLength) ++ a
}

def bigIntegerToIPv6(ipv6Num : BigInteger) : String = {
    val address = InetAddress.getByAddress(bigIntToFixedSizeByteArray(ipv6Num))  
    address.toString.replaceFirst("/", "")
}

Look this(support ipv4 and ipv6):

import java.math.BigInteger
import java.net.{UnknownHostException, InetAddress}
import org.apache.commons.lang.StringUtils

def ipToBigInteger(s: String): BigInteger = {
  try {
    val i = InetAddress.getByName(s)
    val a: Array[Byte] = i.getAddress()
    new BigInteger(1, a)
  } catch {
    case e: UnknownHostException => new BigInteger("-1")
  }
}


def bigIntegerToIP(s: String): String = {
  try {
    //InetAddress.getByAddress(bi.toByteArray).toString.replaceFirst("/", "")
    val bi = new BigInteger(s)
    if (bi.compareTo(new BigInteger("0")) != -1 && bi.compareTo(new   BigInteger("340282366920938463463374607431768211455")) != 1) {
      if (bi.compareTo(new BigInteger("4294967295")) != 1) { // IPV4
        val l = bi.longValue
        String.format("%d.%d.%d.%d",
          bi.shiftRight(24).and(BigInteger.valueOf(0xFF)).intValue: Integer,
          bi.shiftRight(16).and(BigInteger.valueOf(0xFF)).intValue: Integer,
          bi.shiftRight(8).and(BigInteger.valueOf(0xFF)).intValue: Integer,
          bi.and(BigInteger.valueOf(0xFF)).intValue: Integer)
      } else { // IPV6
        String.format("%s:%s:%s:%s:%s:%s:%s:%s",
          Integer.toHexString(bi.shiftRight(112).and(BigInteger.valueOf(0xFFFF)).intValue): java.lang.String,
          Integer.toHexString(bi.shiftRight(96).and(BigInteger.valueOf(0xFFFF)).intValue): java.lang.String,
          Integer.toHexString(bi.shiftRight(80).and(BigInteger.valueOf(0xFFFF)).intValue): java.lang.String,
          Integer.toHexString(bi.shiftRight(64).and(BigInteger.valueOf(0xFFFF)).intValue): java.lang.String,
          Integer.toHexString(bi.shiftRight(48).and(BigInteger.valueOf(0xFFFF)).intValue): java.lang.String,
          Integer.toHexString(bi.shiftRight(32).and(BigInteger.valueOf(0xFFFF)).intValue): java.lang.String,
          Integer.toHexString(bi.shiftRight(16).and(BigInteger.valueOf(0xFFFF)).intValue): java.lang.String,
          Integer.toHexString(bi.and(BigInteger.valueOf(0xFFFF)).intValue): java.lang.String)
      }
    } else
      StringUtils.EMPTY
  } catch {
    case e: UnknownHostException => StringUtils.EMPTY
    case e: NumberFormatException => StringUtils.EMPTY
  }
}


def bigIntegerToIPV6(bi: BigInteger): String = {
  try {
    //InetAddress.getByAddress(bi.toByteArray).toString.replaceFirst("/", "")
    if (bi.compareTo(new BigInteger("0")) != -1 && bi.compareTo(new BigInteger("340282366920938463463374607431768211455")) != 1) {
      String.format("%s:%s:%s:%s:%s:%s:%s:%s",
        Integer.toHexString(bi.shiftRight(112).and(BigInteger.valueOf(0xFFFF)).intValue): java.lang.String,
        Integer.toHexString(bi.shiftRight(96).and(BigInteger.valueOf(0xFFFF)).intValue): java.lang.String,
        Integer.toHexString(bi.shiftRight(80).and(BigInteger.valueOf(0xFFFF)).intValue): java.lang.String,
        Integer.toHexString(bi.shiftRight(64).and(BigInteger.valueOf(0xFFFF)).intValue): java.lang.String,
        Integer.toHexString(bi.shiftRight(48).and(BigInteger.valueOf(0xFFFF)).intValue): java.lang.String,
        Integer.toHexString(bi.shiftRight(32).and(BigInteger.valueOf(0xFFFF)).intValue): java.lang.String,
        Integer.toHexString(bi.shiftRight(16).and(BigInteger.valueOf(0xFFFF)).intValue): java.lang.String,
        Integer.toHexString(bi.and(BigInteger.valueOf(0xFFFF)).intValue): java.lang.String)
    } else
      StringUtils.EMPTY
  } catch {
    case e: UnknownHostException => StringUtils.EMPTY
    case e: NumberFormatException => StringUtils.EMPTY
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM