Is there a way to find mapping between MAC address to IP address in C#. i think RARP should be able to do that, is there an API available in C# for that
In case you are looking for an API based approach and are not able to do a Process.Start() take a look at this:
http://www.codeproject.com/KB/IP/host_info_within_network.aspx
It allows mapping of hostname, IP address and MAC address.
You can use this class
internal class IPAndMac
{
public string IP { get; set; }
public string MAC { get; set; }
}
public class IPMacMapper
{
private static List<IPAndMac> list;
private static StreamReader ExecuteCommandLine(String file, String arguments = "")
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = true;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.FileName = file;
startInfo.Arguments = arguments;
Process process = Process.Start(startInfo);
return process.StandardOutput;
}
private static void InitializeGetIPsAndMac()
{
if (list != null)
return;
var arpStream = ExecuteCommandLine("arp", "-a");
List<string> result = new List<string>();
while (!arpStream.EndOfStream)
{
var line = arpStream.ReadLine().Trim();
result.Add(line);
}
list = result.Where(x => !string.IsNullOrEmpty(x) && (x.Contains("dynamic") || x.Contains("static")))
.Select(x =>
{
string[] parts = x.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
return new IPAndMac { IP = parts[0].Trim(), MAC = parts[1].Trim() };
}).ToList();
}
public static string FindIPFromMacAddress(string macAddress)
{
InitializeGetIPsAndMac();
return list.SingleOrDefault(x => x.MAC == macAddress).IP;
}
public static string FindMacFromIPAddress(string ip)
{
InitializeGetIPsAndMac();
return list.SingleOrDefault(x => x.IP == ip).MAC;
}
}
and use it as
var ipAddress = IPMacMapper.FindIPFromMacAddress("mac-address");
var macAddress = IPMacMapper.FindMacFromIPAddress("ip-address");
Why not spawn a process to invoke rarp
and read in the input stream from the process's output? That's a real cheap simple and cheerful way of doing it...top-of-my-head, it goes something like this:
System.Diagnostics.ProcessStartInfo ps = new System.Diagnostics.ProcessStartInfo("arp", "-a"); ps.CreateNoWindow = false; ps.RedirectStandardOutput = true; using (System.Diagnostics.Process proc = new System.Diagnostics.Process()) { proc.StartInfo = ps; proc.Start(); System.IO.StreamReader sr = proc.StandardOutput; while (!proc.HasExited) ; string sResults = sr.ReadToEnd(); }
Then it's a matter of parsing the sResults
to get the MAC address.