Skip to content

Instantly share code, notes, and snippets.

@timothyklim
Created August 3, 2012 21:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save timothyklim/3251750 to your computer and use it in GitHub Desktop.
Save timothyklim/3251750 to your computer and use it in GitHub Desktop.
IP to long and reverse on Scala
import collection.mutable.ListBuffer
object NetworkUtils {
def ip2Long(ip: String): Long = {
val atoms: Array[Long] = ip.split("\\.").map(java.lang.Long.parseLong(_))
val result: Long = (3 to 0 by -1).foldLeft(0L)(
(result, position) => result | (atoms(3 - position) << position * 8))
result & 0xFFFFFFFF
}
implicit def long2String(value: Long): String = value.toString
def long2IP(ip: Long): String = {
val resultBuilder = new ListBuffer[String]()
var ipBuffer = ip
for (position <- 0 to 3) {
resultBuilder.prepend(ipBuffer & 0xFF)
ipBuffer >>= 8
}
resultBuilder.mkString(".")
}
}
@renpe
Copy link

renpe commented Jul 30, 2014

"1.2.3.4".split("\.").reverse.zipWithIndex.map(a=>a._1.toInt*math.pow(256,a._2).toLong).sum

(0 until 4).map(a=>16909060L / math.pow(256, a).floor.toInt % 256).reverse.mkString(".")

@adatta02
Copy link

adatta02 commented Mar 3, 2016

I only tried "long2ip" but the original gist doesn't compile for me and the comment returns an invalid IP. The answer on http://stackoverflow.com/questions/34798559/how-to-convert-ipv4-addresses-to-from-long-in-scala seems to work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment