Getting IP address, MAC address, and subnet mask of localhost

Determining local IP address is easy, but determining MAC address, and subnet mask in Java has always been one of those hairy problems that sends me Googling. Using some of those same Java utilities, we can add a few Scala-isms and shorten the whole thing up significantly.

To get the IP address we can just statically retrieve an to localhost and get the address String from that .

scala> import

scala> val localhost = InetAddress.getLocalHost
localhost: = mymachine.domain.local/

scala> val localIpAddress = localhost.getHostAddress               
localIpAddress: java.lang.String =

scala> println(localIpAddress)             

Wrapping our localhost address object in a, we can get the MAC address, or hardware address, formatted as an array of bytes, which we can convert to a Scala List, allowing us to format as hex and concatenate with the “:” separator with relatively little effort. Note that NetworkInterface.getNetworkAddress() requires Java 1.6.

scala> val localNetworkInterface = NetworkInterface.getByInetAddress(localhost)
localNetworkInterface: = 
name:en0 (en0) index: 4 addresses:

scala> val localMacAddress = => String.format("%02x",b.asInstanceOf[AnyRef])).mkString(":")
localMacAddress: String = 00:23:32:c6:8a:8a

We can use the same instance to get us the subnet mask by retrieving the addresses for all interfaces (also a Java 1.6-only method) and for each of these retrieve the network prefix length, which essentially represents the subnet mask. We import scala.collection.JavaConversions._ to give us implicit Java-to-Scala list conversions, which I believe was introduced in Scala 1.8.

scala> import scala.collection.JavaConversions._       
import scala.collection.JavaConversions._

scala> val localSubnetCidrs =
localSubnetCidrs: scala.collection.mutable.Buffer[Short] = ArrayBuffer(24, 64)

Hmmm…that’s not quite right. 24 and 64 aren’t what we expect to see for subnet masks. But worry not, we’re on our way, right now we have the CIDR notation version of the subnet masks, in IPv4 and IPv6 respectively. We then just need to filter out the IPv6 address and convert the CIDR notation to our expected format, which I do using the import class from Apache Commons Net

scala> import

scala> val localSubnetAddresses = localSubnetCidrs.filter(l => !(l < 0 || l > 32)).map(c => (new SubnetUtils(""+c)).getInfo.getNetmask)
localSubnetAddresses: scala.collection.mutable.Buffer[java.lang.String] = ArrayBuffer(

scala> println(localSubnetAddresses(0))


, , , , , ,

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>