3

I m developing a software where i need the list of IP address and MAC address of computer through java code. Is there any way to get the list of ip address and mac address?

Thanks

2

2 Answers 2

7

Since JDK 1.6, Java developers are able to access network card detail via NetworkInterface class.

 InetAddress ip; ip = InetAddress.getLocalHost(); System.out.println("Current IP address : " + ip.getHostAddress()); NetworkInterface network = NetworkInterface.getByInetAddress(ip); byte[] mac = network.getHardwareAddress(); System.out.print("Current 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()); 

For multiple ip addresses :

 java.util.Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { NetworkInterface iface = en.nextElement(); List<InterfaceAddress> addrs = iface.getInterfaceAddresses(); //For each network interfaces iterate through each ip address for(InterfaceAddress addr : addrs) { ip = addr.getAddress(); //Process the IP ... 
Sign up to request clarification or add additional context in comments.

1 Comment

This code is ok for single ip in computer, but what if there are multiple ip addresses in a single computer.
1

Sample code to run commands from java program,

 Process p; String cmd="ifconfig-a"; p = Runtime.getRuntime().exec(cmd); BufferedReader br = new BufferedReader( new InputStreamReader(p.getInputStream())); while ((s = br.readLine()) != null) System.out.println("line: " + s); p.waitFor(); System.out.println ("exit: " + p.exitValue()); p.destroy(); 

Output:

line: eth0 Link encap:Ethernet HWaddr 00:13:D3:DE:5A:A4 --->MAC address in linux 

1 Comment

can you please define what is p variable here

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.