I have this function which uses InetAddress
, but the output is occasionally wrong. (example: "::ffff:49e7:a9b2"
will give an incorrect result.)
def IPv6ToBigInteger(ip: String): BigInteger = {
val i = InetAddress.getByName(ip)
val a: Array[Byte] = i.getAddress
new BigInteger(1, a)
}
And the I also have this function
def IPv6ToBigInteger(ip: String): BigInteger = {
val fragments = ip.split(":|\\.|::").filter(_.nonEmpty)
require(fragments.length <= 8, "Bad IPv6")
var ipNum = new BigInteger("0")
for (i <-fragments.indices) {
val frag2Long = new BigInteger(s"${fragments(i)}", 16)
ipNum = frag2Long.or(ipNum.shiftLeft(16))
}
ipNum
}
which appears to have a parsing error because it gives the wrong output unless it is in 0:0:0:0:0:0:0:0
format, but is an based on my IPv4ToLong function:
def IPv4ToLong(ip: String): Long = {
val fragments = ip.split('.')
var ipNum = 0L
for (i <- fragments.indices) {
val frag2Long = fragments(i).toLong
ipNum = frag2Long | ipNum << 8L
}
ipNum
}