Skip to content

Instantly share code, notes, and snippets.

@oluies
Created November 23, 2016 14:23
Show Gist options
  • Save oluies/58b86933974c22782dbcded665f1fb4e to your computer and use it in GitHub Desktop.
Save oluies/58b86933974c22782dbcded665f1fb4e to your computer and use it in GitHub Desktop.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment