Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get localhost network interface in java or scala

Tags:

java

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
like image 768
jonderry Avatar asked Oct 29 '25 12:10

jonderry


2 Answers

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)
like image 78
wingedsubmariner Avatar answered Oct 31 '25 02:10

wingedsubmariner


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
  }
}
like image 24
frostmatthew Avatar answered Oct 31 '25 01:10

frostmatthew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!