jonderry
jonderry

Reputation: 23633

How to get localhost network interface in java or scala

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

Upvotes: 4

Views: 2200

Answers (2)

frostmatthew
frostmatthew

Reputation: 3298

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
  }
}

Upvotes: 2

wingedsubmariner
wingedsubmariner

Reputation: 13667

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)

Upvotes: 6

Related Questions