MAC Address In Java Example
Chapter:
Networking
Last Updated:
22-09-2018 08:33:53 UTC
Program:
/* ............... START ............... */
import java.net.*;
public class JavaMacAddress {
public static void main(String[] args) {
InetAddress ip;
try {
ip = InetAddress.getLocalHost();
System.out.println("IP address : " + ip.getHostAddress());
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
byte[] mac = network.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());
} catch (Exception e) {
e.printStackTrace();
}
}
}
/* ............... END ............... */
Output
IP address : 192.168.1.118
MAC address : 80-86-F2-02-A0-2G
Notes:
-
A media access control address (MAC address) is a unique identifier assigned to network interfaces for communications on the physical network segment.
- Java InetAddress class represents an IP address. The java.net.InetAddress class provides methods to get the IP of any host name.
- InetAddress.getLocalHost() returns the instance of InetAdddress containing local host name and address.
- In the above program ip.getHostAddress() returns the IP address machine in string format.
- NetworkInterface class represents a Network Interface made up of a name, and a list of IP addresses assigned to this interface. It is used to identify the local interface on which a multicast group is joined.
- network.getHardwareAddress() gives the hardware address (usually MAC) of the interface.
Tags
MAC Address, Java, get all mac addresses,how to get mac address of client machine in java, java get ip address from mac address