如何在Scala中将IPv4地址转换为Long或从Long转换

时间:2016-01-14 19:57:09

标签: scala ip ip-address ipv4

我正在寻找一个带有2个函数的基本实用程序,用于在Scala中将IPv4地址转换为Long,例如将“10.10.10.10”转换为168430090的Long表示并返回。诸如此类的基本实用程序存在于许多语言(例如python)中,但似乎需要为JVM的每个人重写相同的代码。

统一IPv4ToLong和LongToIPv4功能的推荐方法是什么?

7 个答案:

答案 0 :(得分:6)

结合leifbattermanElesin Olalekan Fuad的想法,避免乘法和幂次操作:

def ipv4ToLong(ip: String): Option[Long] = Try(
  ip.split('.').ensuring(_.length == 4)
    .map(_.toLong).ensuring(_.forall(x => x >= 0 && x < 256))
    .reverse.zip(List(0,8,16,24)).map(xi => xi._1 << xi._2).sum
).toOption

要以点分格式将Long转换为字符串:

def longToipv4(ip: Long): Option[String] = if ( ip >= 0 && ip <= 4294967295L) {
  Some(List(0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000).zip(List(0,8,16,24))
    .map(mi => ((mi._1 & ip) >> mi._2)).reverse
    .map(_.toString).mkString("."))
} else None

答案 1 :(得分:4)

import java.net.InetAddress
def IPv4ToLong(dottedIP: String): Long = {
  val addrArray: Array[String] = dottedIP.split("\\.")
  var num: Long = 0
  var i: Int = 0
  while (i < addrArray.length) {
    val power: Int = 3 - i
    num = num + ((addrArray(i).toInt % 256) * Math.pow(256, power)).toLong
    i += 1
  }
  num
}

def LongToIPv4 (ip : Long) : String = {
  val bytes: Array[Byte] = new Array[Byte](4)
  bytes(0) = ((ip & 0xff000000) >> 24).toByte
  bytes(1) = ((ip & 0x00ff0000) >> 16).toByte
  bytes(2) = ((ip & 0x0000ff00) >> 8).toByte
  bytes(3) = (ip & 0x000000ff).toByte
  InetAddress.getByAddress(bytes).getHostAddress()
}

scala> IPv4ToLong("10.10.10.10")
res0: Long = 168430090

scala> LongToIPv4(168430090L)
res1: String = 10.10.10.10

答案 2 :(得分:3)

对于ipv4来说,这非常简单:

def ipToLong(ip:String) = ip.split("\\\\.").foldLeft(0L)((c,n)=>c*256+n.toLong)

def longToIP(ip:Long) = (for(a<-3 to 0 by -1) yield ((ip>>(a*8))&0xff).toString).mkString(".")

答案 3 :(得分:3)

试试ipaddr scala library。创建一个IpAddress并获取其长值,如下所示:

val ip1: IpAddress = IpAddress("192.168.0.1")
val ip1Long = ip1.numerical // returns 3232235521L

答案 4 :(得分:2)

我有一个解决这个问题的GitHub要点。要点包含从IP转换为Long的代码,反之亦然。访问https://gist.github.com/OElesin/f0f2c69530a315177b9e0227a140f9c1

以下是代码:

def ipToLong(ipAddress: String): Long = {
   ipAddress.split("\\.").reverse.zipWithIndex.map(a=>a._1.toInt*math.pow(256,a._2).toLong).sum
}

def longToIP(long: Long): String = {
   (0 until 4).map(a=>long / math.pow(256, a).floor.toInt % 256).reverse.mkString(".")
}

享受

答案 5 :(得分:0)

添加到Elesin Olalekan Fuad's答案可以使其更加健壮:

def ipToLong(ip: String): Option[Long] = {
  Try(ip.split('.').ensuring(_.length == 4)
    .map(_.toLong).ensuring(_.forall(x => x >= 0 && x < 256))
    .zip(Array(256L * 256L * 256L, 256L * 256L, 256L, 1L))
    .map { case (x, y) => x * y }
    .sum).toOption
}

def longToIp(ip: Long): Option[String] = {
  if (ip >= 0 && ip <= 4294967295L)
    Some((0 until 4)
      .map(a => ip / math.pow(256, a).floor.toInt % 256)
      .reverse.mkString("."))
  else
    None
}

答案 6 :(得分:0)

我喜欢@jwvh对ipv4ToLong的评论。至于longToIpv4,那就简单一点:

def longToIpv4(v:Long):String =(对于(i <-0至3)收益(v >>(i * 8))&0x000000FF).reverse.mkString(“。”)