Search code examples
c#stringlistip-addressmac-address

Use "arp -a" to retreive MAC address of corresponding IP Adress


I was trying to convert the MAC address of my phone to it's IP address.

var arpStream = ExecuteCommandLine("arp", "-a");
List<string> result = new List<string>();
   while (!arpStream.EndOfStream)
  {
      var line = arpStream.ReadLine().Trim();
      result.Add(line);
  }

Using the above code, I store it in a list in the following form:

  192.168.137.1         2e-bb-58-0a-2f-34     dynamic
  192.168.137.44        a8-3e-0e-61-3f-db     dynamic
  192.168.137.91        d4-63-c6-b2-ac-38     dynamic
  224.0.0.22            01-00-5e-00-00-16     static
  224.0.0.252           01-00-5e-00-00-fc     static

What I can't figure out is, how to retrieve a specific IP for the given MAC. Assume that my phone is the device with the physical address: a8-3e-0e-61-3f-db, how can I store it's IP as a string somewhere?


Solution

  • String s = "";
    for (int i = 3; i < result.Count(); i++)
    {
                    s = Convert.ToString(result[i]);
                    if (s.Contains(macAddress))
                    {
                        break;
                    }
    }
    char[] ip = new char[15];
    StringBuilder ipaddr = new StringBuilder();
    for (int i = 0; s[i].CompareTo(' ') != 0; i++)
    {
                    ipaddr.Append(s[i]);
    }
    return ipaddr;
    

    I used each entry in the result list as a string and looked for my MAC as a substring inside all of the entries.