C#中同一LAN上的MAC地址到IP地址

时间:2010-02-05 00:40:51

标签: c# windows networking tcp

有没有办法在C#中找到MAC地址到IP地址之间的映射。我认为RARP应该能够做到这一点,C#中是否有可用的API

3 个答案:

答案 0 :(得分:2)

为什么不生成一个进程来调用rarp并从进程的输出中读入输入流?这是一种真正廉价的简单而愉快的方式......我的头脑,它是这样的:

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();
}

然后解析sResults以获取MAC地址。

答案 1 :(得分:0)

您可以使用此课程

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;
    }
}

并将其用作

var ipAddress = IPMacMapper.FindIPFromMacAddress("mac-address");
var macAddress = IPMacMapper.FindMacFromIPAddress("ip-address");

答案 2 :(得分:-1)

如果您正在寻找基于API的方法并且无法执行Process.Start(),请查看以下内容:

http://www.codeproject.com/KB/IP/host_info_within_network.aspx

它允许映射主机名,IP地址和MAC地址。