You can use java.net.NetworkInterface.getNetworkInterfaces to get the network interfaces and call getHardwareAddress () to get the MAC address.
You can filter the loopback with if.isLoopBack () (where "if" is the interface object). Also filter out any interface where if.getHardwareAddress () returns null. Then select one. You can sort them by name, if.getName (), and take the first one. For your purposes, this does not really matter if it is the actual interface used to download your files or not, just so that you somehow identify the computer. Finally, if.getHardwareAddress () gives you an array of bytes with a MAC address. If you prefer String, format each byte with "% 02x" .format (byte) and append them to the ":" delimiter.
As suggested in another answer, it is better to use a PersistenceService.
However, using a MAC address can be useful if you want to store different data for the same user on different computers in the event that the user has the same / homedirs files on each computer. You can use the MAC address as part of the URL that you pass to PersistenceService # create () and get (). Useful if you need data for each computer, and not data for each user.
A brief example of Scala -code:
def computerID: String = { try { // mac address of first network interface return java.net.NetworkInterface.getNetworkInterfaces .filter(!_.isLoopback) .filter(_.getHardwareAddress != null) .toList.sortBy(_.getName).head .getHardwareAddress.map("%02x".format(_)).mkString(":") } catch { case _ => return "0" // no mac address available? use default "0" } }
source share