Search code examples
regexgrailsgroovymac-address

Getting Mac Address in Groovy


Just want to ask if there's a way of getting your local machine's Mac address as String. I need to save my local machine's mac address into a domain class. I tried using this code to get my Mac address:

String address = "ifconfig".execute().text()

But this line it also returns a lot of details about my ip address, all I need to get is the Mac Address which is found after the substring "HWaddr". I'm thinking if i could extract this substring using regex but I am not sure how to do it.


Solution

  • You can get the MAC address for an interface using java.net.NetworkInterface. Note that it is possible to have multiple hardware network interfaces, so it's possible to have more than one MAC address. In addition, most machines will have at least one interface without a hardware address: the loopback interface.

    This will get a list of all the MAC addresses as Strings, including nulls for interfaces without a MAC address:

    import java.net.NetworkInterface 
    def macs = NetworkInterface.networkInterfaces.collect { iface -> 
        iface.hardwareAddress?.encodeHex().toString()
    }