How to check if a string is IPv4 or IPv6 or invalid in Scala

1 Answer

0 votes
import java.net.{InetAddress, UnknownHostException}
import java.net.Inet4Address
import java.net.Inet6Address

def checkIpAddress(s: String): String = {
  try {
    val ip = InetAddress.getByName(s)

    ip match {
      case _: Inet4Address => "IPv4"
      case _: Inet6Address => "IPv6"
      case _               => "Invalid"
    }

  } catch {
    case _: UnknownHostException => "Invalid"
  }
}

@main def run(): Unit = {
  println(checkIpAddress("112.128.1.2"))
  println(checkIpAddress("2001:0dc7:85b2:0000:0000:6d3e:0380:8651"))
  println(checkIpAddress("999.999.999.999"))
  println(checkIpAddress("abc"))
}




/*
run:

IPv4
IPv6
Invalid
Invalid

*/

 



answered Jan 20 by avibootz

Related questions

...