Created
January 10, 2020 12:45
-
-
Save jogHar/e6c191542c19cf5a7141a00f8d172f44 to your computer and use it in GitHub Desktop.
Using this program you can find machine MAC address of windows and ubuntu
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.net.InetAddress; | |
import java.net.NetworkInterface; | |
/** | |
* @author jogHar | |
*/ | |
public class SystemMacAddress { | |
public static String getSystemMac(){ | |
try{ | |
String OSName= System.getProperty("os.name"); | |
if(OSName.contains("Windows")){ | |
return (getMAC4Windows()); | |
} else{ | |
String mac=getMAC4Linux("wlp2s0"); | |
if(mac==null){ | |
mac=getMAC4Linux("enp1s0"); | |
} | |
return mac; | |
} | |
} | |
catch(Exception E){ | |
System.err.println("System Mac Exp : "+E.getMessage()); | |
return null; | |
} | |
} | |
/** | |
* Method for get MAc of Linux Machine | |
*/ | |
private static String getMAC4Linux(String name){ | |
try { | |
NetworkInterface network = NetworkInterface.getByName(name); | |
byte[] mac = network.getHardwareAddress(); | |
StringBuilder sb = new StringBuilder(); | |
for (int i = 0; i < mac.length; i++){ | |
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "")); | |
} | |
return (sb.toString()); | |
} | |
catch (Exception E) { | |
System.err.println("System Linux MAC Exp : "+E.getMessage()); | |
return null; | |
} | |
} | |
/** | |
* Method for get Mac Address of Windows Machine | |
*/ | |
private static String getMAC4Windows(){ | |
try{ | |
InetAddress addr =InetAddress.getLocalHost(); | |
NetworkInterface network = NetworkInterface.getByInetAddress(addr); | |
byte[] mac = network.getHardwareAddress(); | |
StringBuilder sb = new StringBuilder(); | |
for(int i=0;i<mac.length;i++){ | |
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "")); | |
} | |
return sb.toString(); | |
} | |
catch(Exception E){ | |
System.err.println("Windows MAC : "+E.getMessage()); | |
return null; | |
} | |
} | |
public static void main(String[] args) { | |
String macAddress = getSystemMac(); | |
System.out.println("System Mac Address : "+macAddress); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment