Senin, 29 Februari 2016

How To Get Mac Address Using Java Network

Following the Java Network example code to display a mac address in hexadecimal format.

Source Code


File Name : GetMacAddressDemo.java

import java.net.InetAddress;
import java.net.NetworkInterface;

public class GetMacAddressDemo {

 public static void main(String[] args) throws Exception {
     InetAddress inetAddress = InetAddress.getLocalHost();
     System.out.println("IP address : " + inetAddress.getHostAddress());

     NetworkInterface networkInteface = NetworkInterface.getByInetAddress(inetAddress);
     byte[] mac = networkInteface.getHardwareAddress();
     System.out.print("MAC address : ");

     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());
   }
}


Output


IP address : 192.168.1.101
MAC address : 68-5D-43-93-07-3D

Tidak ada komentar:

Posting Komentar