Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 701
Garren S Avatar asked Nov 29 '22 10:11

Garren S


1 Answers

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
like image 77
tcat Avatar answered Dec 05 '22 10:12

tcat