Skip to content

Instantly share code, notes, and snippets.

@farico
Forked from timothyklim/ip.scala
Last active August 29, 2015 14:08
Show Gist options
  • Save farico/49586172d9f0bbe9b3e5 to your computer and use it in GitHub Desktop.
Save farico/49586172d9f0bbe9b3e5 to your computer and use it in GitHub Desktop.
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(".")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment