Scala: How to get your computer’s IP address

Scala FAQ: How do I get my computer system’s IP address using Scala?

Possible solution: The following code shows one way to get your computer’s IP address using Scala (and Java):

import java.net.InetAddress

val ia: InetAddress = InetAddress.getLocalHost
val hostname: String = ia.getHostName

Here’s what that code looks like in the Scala REPL on my system:

scala> val ip: InetAddress = InetAddress.getLocalHost
val ip: java.net.InetAddress = Alvins-Mac/192.168.0.13
                                                                                                                                  
scala> val hostname: String = ip.getHostName
val hostname: String = Alvins-Mac

I’m not 100% confident in that solution, but it does seem to match the output I see with the ifconfig -a command, so that’s promising. Be sure to test it on your systems to make sure it works as desired. Also, be aware that this code can throw a java.net.UnknownHostException, so you’ll want to account for that.