Address Resolution Protocol in Java

Submitted by Karthikeyan on
This program displays the MAC address of the network interface.
This program accepts the System name in LAN as Input and displays the IP Address and Physics Address of the system.

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;

public class MacAddress {
    public static void main(String[] args)
    {
        try
        {
            Scanner console = new Scanner(System.in);
            System.out.println("Enter System Name: ");
            String ipaddr = console.nextLine();
            InetAddress address = InetAddress.getByName(ipaddr);
            System.out.println("address = "+address);
            NetworkInterface ni = NetworkInterface.getByInetAddress(address);
            if (ni!=null)
            {
                byte[] mac = ni.getHardwareAddress();
                if (mac != null)
                {
                    System.out.print("MAC Address : ");
                    for (int i=0; i < mac.length; i++)
                    {
                        System.out.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" :"");
                    }
                }
                else
                {
                    System.out.println("Address doesn't exist or is not accessible/");
                    
                    }
                }
            else
            {
                System.out.println("Network Interface for the specified address is not found");
            }
        }
        catch(UnknownHostException | SocketException e)
        {
        }
    }    
}

Sample output


Enter System Name: 
myhomepc
address = myhomepc/169.254.189.225
MAC Address : 08-00-27-00-C4-03