How to obtain the localhost network interface in Java or Scala

I'm trying to get the MAC address of my machine in the scala application There are several results when searching, but they all use something similar to the following, involving InetAddress Getlocalhost(), followed by networkinterface getByInetAddress(…): Get MAC address on local machine with Java

My problem is that the result is 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

Solution

Getbyinetaddress has the same destructive behavior on my machine, but you can use getnetworkinterfaces instead:

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

NetworkInterface.getNetworkInterfaces.asScala map (_.getHardwareAddress) filter (_ != null)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>