Main Menu
Home
Contact Us
Obtaining Mac Addresses in Java

The following Java class is handy for folks looking for a list of mac addresses for network interfaces. It uses the Hex class from the apache commons codec in order to parse the mac from byte format to hex. Enjoy!

 

import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import org.apache.commons.codec.binary.Hex; 
/*


* @author Christopher Duke, Research Information Systems 
* @email chris [ at ]  informationsystems  .  ie 
*/ 
public class getMacAddresses {

    
private List< char[] > macAddressesChars = new ArrayList< char [] >();
    
private List< String > macAddressesString = new ArrayList< String >();

 
public getMacAddresses()    
  {       
   
try        
   
{            
     
Enumeration eth = NetworkInterface.getNetworkInterfaces();

     
while (eth.hasMoreElements())            
      {            
       
NetworkInterface eth0 = (NetworkInterface) eth.nextElement();
               
       
byte mac [] = eth0.getHardwareAddress();

       
// We may occasionally get null references so we have to avoid a null pointer
        // error by checking if mac is null
       
if (!(mac == null))                
        {                    
         
// Add the addresses to the macAddresses Vector
         
macAddressesChars.add(Hex.encodeHex(mac));                
       
}            
      }             
     
     
// Put the contents of the mac address list into another list in String format
     
for (int count = 0; count < macAddressesChars.size(); count++)
      {                
       
// Convert the character array to a string and store in temporary String                
       
String tempString = new String (macAddressesChars.get(count));                
       
// Add the temporary String to the String List                
       
macAddressesString.add(tempString);            
     
}         
    }        
   
catch (Exception e)        
    {            
     
e.printStackTrace();        
   
}    
  }     
 
 
public List< String > getMacList()    
  {        
   
return macAddressesString;    
 
}  

}