I want to get the MAC of the ethernet card (for product key) I tried using this kind of solution and searched here, the problem is that when all the networking is disconnected (ethernet and wifi) it returns empty MAC adress. I rather get the adress of the ethernet even if it's disconnected.
Thanks!!
public static void main(String[] args)
{
InetAddress ip;
try {
ip = InetAddress.getLocalHost();
System.out.println("The mac Address of this machine is :" + ip.getHostAddress());
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
byte[] mac = network.getHardwareAddress();
System.out.print("The mac address is : ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++){
sb.append(String.format("%02X%s", mac[i],(i< mac.length - 1)?"-":""));
}
System.out.println(sb.toString());
}
catch (UnknownHostException e) {
e.printStackTrace();
}
catch (SocketException e) {
e.printStackTrace();
}
}
}
First, let's get the MAC address for our machine's localhost: InetAddress localHost = InetAddress. getLocalHost(); NetworkInterface ni = NetworkInterface. getByInetAddress(localHost); byte[] hardwareAddress = ni.
The MAC address isn't in the client request headers, so the only thing you've got in the clients IP address to use. You can't get the MAC address of the client unless the server is on the same network segment as the client.
To get the MAC address, pass the parameter 'getmac' which returns the MAC address of the client. 'getmac' is a CMD command to get the MAC address.
A MAC (Media Access Control) address, sometimes referred to as a hardware or physical address, is a unique, 12-character alphanumeric attribute that is used to identify individual electronic devices on a network. An example of a MAC address is: 00-B0-D0-63-C2-26.
Using InetAddress
binds you to look in a list of IP addresses. If you have none because the interfaces are all disconnected, then you can't loop over such interfaces.
You should try with NetworkInterface
class.
public class MacAddressTest
{
public static void main(String[] args) throws Exception
{
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements())
{
NetworkInterface nif = interfaces.nextElement();
byte[] lBytes = nif.getHardwareAddress();
StringBuffer lStringBuffer = new StringBuffer();
if (lBytes != null)
{
for (byte b : lBytes)
{
lStringBuffer.append(String.format("%1$02X ", new Byte(b)));
}
}
System.out.println(lStringBuffer);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With