Created
August 3, 2012 21:34
-
-
Save timothyklim/3251750 to your computer and use it in GitHub Desktop.
IP to long and reverse on Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
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.