1

I want to get IP Address and MAC address of my pc. I used the following code to do so:

InetAddress ip; try { 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()); } catch (UnknownHostException e) { e.printStackTrace(); } catch (SocketException e){ e.printStackTrace(); } 

It worked too, but some times the same code prints IP as 127.0.0.1 and doesn't print any mac address. How come?

1
  • this code is running on a applet or java app at client or on your server? Commented Sep 10, 2013 at 8:59

1 Answer 1

4

127.0.0.1 is the loopback address which always exists (*).

A better way of getting the value would be getting all the network interfaces (http://docs.oracle.com/javase/6/docs/api/java/net/NetworkInterface.html#getNetworkInterfaces()) and filtering out the ones whose IP begins with 127.

(*) Except on windows machines where the network cable is disconnected...

Sign up to request clarification or add additional context in comments.

1 Comment

i want to identify client's pc... here i m getting mac address from ip i got InetAddress.getLocalHost().. which is sometimes giving loopback address.... is there any way of gettig mac without ip

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.