Android: Howto find the hardware MAC address of a remote host

I recently needed to find the MAC address of a remote host in my LAN by its IP address.

Unfortunately, Java/Android does not offer an API to find a MAC address by IP. :-(
The DatagramPacket class does not reveal this information for the source host, either.

But Android is Linux, and hence we can try to find the MAC by accessing the ARP cache information!

If we take a look at /proc/net/arp, we can find a table like this:

IP address       HW type     Flags       HW address            Mask     Device    0x1         0x2         00:04:20:06:55:1a     *        eth0    0x1         0x2         00:22:43:ab:2a:5b     *        eth0

So we can use a simple helper method that reads this file and returns the MAC for a specific IP address:

	 * Try to extract a hardware MAC address from a given IP address using the
	 * ARP cache (/proc/net/arp).<br>
	 * <br>
	 * We assume that the file has this structure:<br>
	 * <br>
	 * IP address       HW type     Flags       HW address            Mask     Device
	 *    0x1         0x2         00:04:20:06:55:1a     *        eth0
	 *    0x1         0x2         00:22:43:ab:2a:5b     *        eth0
	 * @param ip
	 * @return the MAC from the ARP cache
	public static String getMacFromArpCache(String ip) {
		if (ip == null)
			return null;
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader("/proc/net/arp"));
			String line;
			while ((line = br.readLine()) != null) {
				String[] splitted = line.split(" +");
				if (splitted != null && splitted.length >= 4 && ip.equals(splitted[0])) {
					// Basic sanity check
					String mac = splitted[3];
					if (mac.matches("..:..:..:..:..:..")) {
						return mac;
					} else {
						return null;
		} catch (Exception e) {
		} finally {
			try {
			} catch (IOException e) {
		return null;

If you like my work, buy me a beer. (Suggested: 3€ for a beer, or more for more beer ;-) )

Tags: , , ,

Leave a Reply