简体   繁体   English

IPv6ToBigInteger

[英]IPv6ToBigInteger

I have this function which uses InetAddress , but the output is occasionally wrong.我有这个使用InetAddress的 function ,但 output 偶尔会出错。 (example: "::ffff:49e7:a9b2" will give an incorrect result.) (例如: "::ffff:49e7:a9b2"将给出不正确的结果。)

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我也有这个 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:这似乎有一个解析错误,因为它给出了错误的 output 除非它是0:0:0:0:0:0:0:0格式,但它基于我的 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
    }

This这个

ipNum = frag2Long | ipNum << 8L

is

ipNum = (frag2Long | ipNum) << 8L

not不是

ipNum = frag2Long | (ipNum << 8L)

[ And please use foldLeft rather than var and while ] [请使用foldLeft而不是varwhile ]

Interesting challenge: transform IP address strings into BigInt values, allowing for all legal IPv6 address forms.有趣的挑战:将 IP 地址字符串转换为BigInt值,允许所有合法的 IPv6 地址 forms。

Here's my try.这是我的尝试。

import scala.util.Try

def iPv62BigInt(ip: String): Try[BigInt] = Try{
  val fill = ":0:" * (8 - ip.split("[:.]").count(_.nonEmpty))
  val fullArr =
    raw"((?<=\.)(\d+)|(\d+)(?=\.))".r
      .replaceAllIn(ip, _.group(1).toInt.toHexString)
      .replace("::", fill)
      .split("[:.]")
      .collect{case s if s.nonEmpty => s"000$s".takeRight(4)}

  if (fullArr.length == 8) BigInt(fullArr.mkString, 16)
  else throw new NumberFormatException("wrong number of elements")
}

This is, admittedly, a bit lenient in that it won't catch all all non-IPv6 forms, but that's not a trivial task using tools like regex.诚然,这有点宽松,因为它不会捕获所有非 IPv6 forms,但使用正则表达式之类的工具并不是一件容易的事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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