Search code examples
javawebjava-web-startmac-address

How Java WebStart application Obtain the MAC address for accessing my webpage


I am writing a java webstart application to deploy from website so users can click and run my software. I need to have a kind of unique machine identification to avoid abusing the accessing of the files. I would like to use the client's MAC address as a unique key so that the server can ensure that no client downloads too much.

Of course, a user may have multiple network cards, so how can my Java application determine the MAC address of the network card that the user is using to access my web site?


Solution

  • You can use java.net.NetworkInterface.getNetworkInterfaces to obtain the network interfaces, and call getHardwareAddress() on them to get the MAC address.

    You may want to filter out loopback with if.isLoopBack() (where "if" is the interface object). Also filter out any interface where if.getHardwareAddress() returns null. Then pick out one. You could sort them by name, if.getName(), and take the first one. For your purposes it doesn't really matter if it is the actual interface used to download your files or not, just that you can identify the computer somehow. Finally if.getHardwareAddress() gives you an array of bytes with the MAC address. If you'd rather have a String, format each byte with "%02x".format(byte) and join them with a ":" as separator.

    As suggested in another answer it may be better to use PersistenceService.

    Using the MAC address can however be useful if you want to persist different data for the same user on different computers in the case where the user has the same files/homedirs on each computer. You can use the MAC address as part of the URL you pass to PersistenceService#create() and get(). Useful if you want per-computer data rather than per-user data.

    Short example 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"
      }
    }