Gary Sieling

Get current IP addresses in Scala

The following example will print out all of the IP addresses your machine has (i.e. IPv4/IPv6 and for each network adapter)

val e = NetworkInterface.getNetworkInterfaces
while(e.hasMoreElements)
{
  val n = e.nextElement match {
    case e: NetworkInterface => e
    case _ => ???
  }
  val ee = n.getInetAddresses
  while (ee.hasMoreElements) {
    ee.nextElement match {
      case e: InetAddress => println(e.getHostAddress)
      case _ => ???
    }
  }
}

Here is an example output:

fe80:0:0:0:1240:f3ff:feaf:6848%en1
192.168.1.2
fe80:0:0:0:0:0:0:1%lo0
0:0:0:0:0:0:0:1
127.0.0.1
Exit mobile version