In this code snippet, you will learn how to get an IP Address, computer name, and MAC address in a Windows OS environment using Java.
We are going to use the namespaces below in order for this program to execute and run.
import java.net.InetAddress; import java.net.NetworkInterface;
Java Program to Get IP address, computer name, and MAC address
package mp; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; class Main { public static void main(String[] args) { try { InetAddress inetAddress = InetAddress.getLocalHost(); String hostName = inetAddress.getHostName(); //Get Host Name String macAddress = ""; String ipAddress = inetAddress.getHostAddress(); // Get IP Address //Get MAC Address NetworkInterface network = NetworkInterface.getByInetAddress(inetAddress); byte[] macArray = network.getHardwareAddress(); StringBuilder str = new StringBuilder(); // Convert the macArray to String for (int i = 0; i < macArray.length; i++) { str.append(String.format("%02X%s", macArray[i], (i < macArray.length - 1) ? " ": "")); macAddress = str.toString(); } System.out.println("Host Name: " + hostName); System.out.println("IP Address: " + ipAddress); System.out.println("MAC Address: " + macAddress); } catch(SocketException e) { System.out.println(e.getMessage()); } catch(UnknownHostException e) { e.printStackTrace(); } } }
Output
Host Name: CPCOM1929718
IP Address: 192.168.11.158
MAC Address: 81 F1 D3 A3 B6 36
Blog Hero
Hi,
Is this possible to get IP address from MAC address in java program.
I need to program the same as I have an Mac address we need to find out the IP address for the same.
I don’t think it’s possible. regards