Monday, August 15, 2016

Get IP address by MAC address in C#

Sometimes it happens that you need to access device in the network by IP address. But unfortunately, it is not every time possible, e.g the device does not have static IP. In such case you can use device's MAC address to find it in the network.

Address Resolution Protocol 

Displays and modifies entries in the Address Resolution Protocol (ARP) cache, which contains one or more tables that are used to store IP addresses and their resolved Ethernet or Token Ring physical addresses. There is a separate table for each Ethernet or Token Ring network adapter installed on your computer.
So we are going to use following arp-command to get all the entries and filter them by specified MAC address.

arp -a

For more option use following link ARP Documentation.

.NET implementation


ArpEntity.cs


namespace ArpExample
{
    public class ArpEntity
    {
        public string Ip { get; set; }

        public string MacAddress { get; set; }

        public string Type { get; set; }
    }
}

ArpHelper.cs


using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;

namespace ArpExample
{
    public class ArpHelper
    {
        public List<ArpEntity> GetArpResult()
        {
            var p = Process.Start(new ProcessStartInfo("arp", "-a")
            {
                CreateNoWindow = true,
                UseShellExecute = false,
                RedirectStandardOutput = true
            });

            var output = p?.StandardOutput.ReadToEnd();
            p?.Close();

            return ParseArpResult(output);
        }

        private List<ArpEntity> ParseArpResult(string output)
        {
            var lines = output.Split('\n').Where(l => !string.IsNullOrWhiteSpace(l));

            var result =
                (from line in lines
                 select Regex.Split(line, @"\s+")
                    .Where(i => !string.IsNullOrWhiteSpace(i)).ToList()
                    into items
                 where items.Count == 3
                 select new ArpEntity()
                 {
                     Ip = items[0],
                     MacAddress = items[1],
                     Type = items[2]
                 });

            return result.ToList();
        }
    }
}

IpFinder.cs


using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace ArpExample
{
    public class IpFinder
    {
        public string FindIpAddressByMacAddress(string macAddress)
        {
            List<ArpEntity> arpEntities = new ArpHelper().GetArpResult();

            return arpEntities.FirstOrDefault(a => a.MacAddress == macAddress)?.Ip;
        }
    }
}

Troubleshooting 

Recently I figured out that the solution described in the article sometimes might fail. I wrote the article with the fix. Please find it using the link Get IP address by MAC address in C#. Updating ARP table