4

I'm trying to get the MAC address for my machine inside a scala application. There are several results when searching, but they all use something like the following, involving InetAddress.getLocalHost() followed by NetworkInterface.getByInetAddress(...): Get MAC address on local machine with Java

My problem is that the result ends up being null:

val localhost = InetAddress.getLocalHost
println(s"lh: $localhost")
val localNetworkInterface = NetworkInterface.getByInetAddress(localhost)
println(s"lni: $localNetworkInterface")

>>lh: ubuntu/127.0.1.1
>>lni: null
Community
  • 1
  • 1
jonderry
  • 23,013
  • 32
  • 104
  • 171
  • You're getting `null` because there is no MAC address for the loopback interface (I've edited my answer to check interface name, which you should be able to obtain easily enough) – frostmatthew May 27 '14 at 23:54

2 Answers2

6

getByInetAddress has the same broken behavior on my machine, but you can use getNetworkInterfaces instead:

import java.net._
import scala.collection.JavaConverters._

NetworkInterface.getNetworkInterfaces.asScala map (_.getHardwareAddress) filter (_ != null)
wingedsubmariner
  • 13,350
  • 1
  • 27
  • 52
2

This will check each interface and assign the MAC address if the display name is eth0. Replace eth0 with the name of the interface you want the MAC address of (can view interfaces on Linux with ifconfig - the loopback address (localhost) does not have a hardware address)

import java.net.NetworkInterface
var macAddress = Array.empty[Byte]
val interfaces = NetworkInterface.getNetworkInterfaces
while (interfaces.hasMoreElements) {
  val element = interfaces.nextElement
  if (element.getDisplayName.equalsIgnoreCase("eth0")) {
    macAddress = element.getHardwareAddress
  }
}
frostmatthew
  • 3,260
  • 4
  • 40
  • 50