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?
Combining the ideas from leifbatterman and Elesin Olalekan Fuad and avoiding multiplication and power operations:
def ipv4ToLong(ip: String): Option[Long] = Try(
ip.split('.').ensuring(_.length == 4)
.map(_.toLong).ensuring(_.forall(x => x >= 0 && x < 256))
.reverse.zip(List(0,8,16,24)).map(xi => xi._1 << xi._2).sum
).toOption
To convert Long to String in dotted format:
def longToipv4(ip: Long): Option[String] = if ( ip >= 0 && ip <= 4294967295L) {
Some(List(0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000).zip(List(0,8,16,24))
.map(mi => ((mi._1 & ip) >> mi._2)).reverse
.map(_.toString).mkString("."))
} else None
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With