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):


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: = Alvins-Mac/
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, so you’ll want to account for that.