B4J Code Snippet Get all MAC Addresses on Windows/Linux

Discussion in 'B4J Code Snippets' started by inakigarm, Sep 18, 2017.

  1. inakigarm

    inakigarm Well-Known Member Licensed User

    I need for an app to set a unique database index and computer hardware based. I've searched for this info in the Forum and I found the jGetMAC library from @giga and this post from @Erel

    The jGetMAC library only returns one MAC Address (and I've 5 MAC Addresses/interfaces on my windows system) and the returned MAC doesn't correspond to the Eth interface/nor Wifi interface.

    So I've adapted the @Erel code to display only the interfaces which have MAC Addresses (independently if the interfaces are up/down or have IP address assigned to it).

    Java class info on http://docs.oracle.com/javase/8/docs/api/java/net/NetworkInterface.html

    Sub AppStart (Form1 As Form, Args() As String)

    Dim jo As JavaObject = Me

    End Sub

    Sub Application_Error (Error As Exception, StackTrace As StringAs Boolean
    Return True
    End Sub
    #if JAVA

    import java.net.NetworkInterface;
    import java.util.Enumeration;

    public static void PrintAllInterfaces() throws Exception {
          for (Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); e.hasMoreElements();)
              NetworkInterface network = e.nextElement();
            byte[] mac = network.getHardwareAddress();
                    if (mac != null)  {
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < mac.length; i++) {
                              sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));       
                        //Interface properties
                        System.out.println("Current MAC address : " + sb.toString() +"\r\n");
    #End If
    Log results:

    Current MAC address : 20-6A-8A-A4-B7-89
    Realtek PCIe GBE Family Controller #2
    Current MAC address : 5C-93-A2-C8-5E-CB
    Qualcomm Atheros AR956x Wireless Network Adapter
    Current MAC address : 1E-93-A2-C8-5E-CB
    Adaptador virtual directo Wi-Fi de Microsoft
    Current MAC address : 5E-93-A2-C8-5E-CB
    Adaptador virtual de red hospedada de Microsoft
    Current MAC address : 00-00-00-00-00-00-00-E0
    Adaptador ISATAP de Microsoft
    Current MAC address : 00-00-00-00-00-00-00-E0
    Adaptador ISATAP de Microsoft #3
    Current MAC address : 0A-00-27-00-00-00
    VirtualBox Host-Only Ethernet Adapter #2
    Current MAC address : 00-00-00-00-00-00-00-E0
    Adaptador ISATAP de Microsoft #4
    Current MAC address : 02-00-4C-4F-4F-50
    Npcap Loopback Adapter
    Last edited: Sep 18, 2017
    giga, jinyistudio, rboeck and 5 others like this.
  2. giga

    giga Well-Known Member Licensed User

    Good job! I have needed to update some of my libraries but no time.:(
    inakigarm likes this.