Thursday, March 7, 2013

Retrieving IP address of each Interface through MAC address for a host machine


public static void main(String args[]) throws Exception {
System.out.println(getIPFromMac("54DE06EA540A"));
}

/**

* @param macAddress
*            should be in byte format without non-numeric values
*            eg:0123456789AB
* @return
* @throws SocketException
*/
static String getIPFromMac(String macAddress) throws SocketException {
Enumeration netintfaces = java.net.NetworkInterface
.getNetworkInterfaces();
HashMap macIpMapper = new HashMap();
while (netintfaces.hasMoreElements()) {
try {
NetworkInterface ninterfaces = netintfaces.nextElement();
String mac = DatatypeConverter.printHexBinary((ninterfaces
.getHardwareAddress()));
Enumeration netIpaddresses = ninterfaces
.getInetAddresses();
while (netIpaddresses.hasMoreElements()) {
try {
InetAddress ip = netIpaddresses.nextElement();
String ipStr = ip.getHostAddress();
macIpMapper.put(mac, ipStr);
} catch (Exception e) {
continue;
}
}
} catch (Exception e) {
continue;
}
}
return macIpMapper.get(macAddress);
}

No comments:

Post a Comment