简体   繁体   中英

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?

I'm assuming you've got the list of strings somehow ( ExecuteCommandLine method) and want to be able to filter it based on arp value. Regex can be an option then:

void Main()
{
    // just setting it up for testing
    List<string> result = new List<string>();
    result.Add("192.168.137.1         2e-bb-58-0a-2f-34     dynamic");
    result.Add("192.168.137.44        a8-3e-0e-61-3f-db     dynamic");
    result.Add("224.0.0.22            01-00-5e-00-00-16     static");
    result.Add("224.0.0.22            01-00-5e-00-00-16     static");
    result.Add("192.168.137.91        d4-63-c6-b2-ac-38     dynamic");
    result.Add("224.0.0.22            01-00-5e-00-00-16     static");
    result.Add("224.0.0.252           01-00-5e-00-00-fc     static");

    // this is the part you want
    ConcurrentDictionary<string,string> arps = new ConcurrentDictionary<string, string>();
    foreach (var s in result)
    {
        var matches = Regex.Match(s, @"((?:\d+\.?){4})\s+((?:[0-9a-f]{2}-?){6}).*");        
        arps.TryAdd(matches.Groups[2].Value, matches.Groups[1].Value);
    }

    Console.WriteLine(arps["01-00-5e-00-00-16"]);
}

note: opting for dictionary here has benefits as well as drawbacks. you will get O(1) element access times, but you can't have duplicate MAC addresses there. Without knowing your specific use case it's a bit hard to say whether this tradeoff will apply to you, I'm just pointing this out as an option.

You can use a Dictionary data structure in C# to hold key-value pair information in your case it is Ipaddress-Macaddress information

在此处输入图片说明

Usage

var macofIpaddress = dict["192.168.137.1"];

Code

string output = "";
var proc = new ProcessStartInfo("cmd.exe", "/c arp -a")
{
      CreateNoWindow = true,
      UseShellExecute = false,
      RedirectStandardOutput = true,
      RedirectStandardError = true,
      WorkingDirectory = @"C:\Windows\System32\"
};
Process p = Process.Start(proc);
p.OutputDataReceived += (sender, args1) => { output += args1.Data + Environment.NewLine; };
p.BeginOutputReadLine();
p.WaitForExit();


var dict = new Dictionary<string, string>();
var lines = output.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

foreach(var line in lines)
{
      if (line.Contains("static") || line.Contains("dynamic"))
      {
         var elements = line.Split(new string[] { "    " }, StringSplitOptions.RemoveEmptyEntries);
        var ipAdd =   elements[0].Trim();
        var macAdd = elements[1].Trim();
        dict.Add(ipAdd,macAdd);
      }



}

Output :

在此处输入图片说明

You can create a model class that will store the IP information like :

public class DeviceIPAddress
{
    public string IPv4 { get; set; }

    public string MAC { get; set; }

    public string IPType { get; set; }
}

Now, we can use this model to parse the provided list, in which will make it easier for us to handle :

var ips = new List<DeviceIPAddress>();

foreach (var ip in result)
{
    var info = ip.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
    ips.Add(new DeviceIPAddress { IPv4 = info[0].Trim(), MAC = info[1].Trim(), IPType = info[2].Trim() });
}

now using the ips list, we can manage the received data easily :

var getIP = ips.First(x => x.MAC.Equals("a8-3e-0e-61-3f-db", StringComparison.InvariantCultureIgnoreCase));
// call getIP.IPv4 will to get the IP 192.168.137.44
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM