Search code examples
scalaipip-addressipv4

How to Convert IPv4 Addresses to/from Long in Scala


I was looking for a basic utility with 2 functions to convert IPv4 Addresses to/from Long in Scala, such as "10.10.10.10" to its Long representation of 168430090 and back. A basic utility such as this exists in many languages (such as python), but appears to require re-writing the same code for everyone for the JVM.

What is the recommended approach on unifying IPv4ToLong and LongToIPv4 functions?


Solution

  • 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