简体   繁体   English

C#通过本地IP获取本地MAC地址(多个接口)

[英]C# get local MAC address by local IP (multiple interfaces)

I have 4 Ethernet interfaces in my computer (getting the information by ipconfig /all) 我的计算机中有4个以太网接口(通过ipconfig / all获取信息)

For example: 例如:
1) IP: 192.168.15.161 , MAC: 00-E2-4C-98-18-89 1)IP: 192.168.15.161 ,MAC: 00-E2-4C-98-18-89
2) IP: 172.168.11.126 , MAC: 00-FF-4C-98-18-44 2)IP: 172.168.11.126 ,MAC: 00-FF-4C-98-18-44
3) IP: 10.0.13.136 , MAC: 00-EE-89-98-13-44 3)IP: 10.0.13.136 ,MAC: 00-EE-89-98-13-44
4) IP: 195.22.18.146 , MAC: 00-12-89-98-13-33 4)IP: 195.22.18.146 ,MAC: 00-12-89-98-13-33

I need a function that returns the MAC address when given IP. 我需要一个在给定IP时返回MAC地址的函数。

For example getMacByIP("192.168.15.161") will return "00-E2-4C-98-18-89" 例如, getMacByIP("192.168.15.161")将返回"00-E2-4C-98-18-89"

Using arp is not working for local! 使用arp不适用于本地!

For example arp -a will not give the local address with MAC 例如, arp -a将不提供带有MAC的本地地址
So all the questions/answers like here are not helping me. 因此, 这里的所有问题/答案都对我没有帮助。

I've searched a lot over the internet before asking this question. 在问这个问题之前,我已经在互联网上进行了很多搜索。

EDIT: 编辑:

This answer: ( link ) not helping me 这个答案:( 链接 )没有帮助我

public static string GetMacAddressUsedByIp(string ipAddress)
    {
        var ips = new List<string>();
        string output;

        try
        {
            // Start the child process.
            Process p = new Process();
            // Redirect the output stream of the child process.
            p.StartInfo.UseShellExecute = false;

            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.FileName = "ipconfig";
            p.StartInfo.Arguments = "/all";
            p.Start();
            // Do not wait for the child process to exit before
            // reading to the end of its redirected stream.
            // p.WaitForExit();
            // Read the output stream first and then wait.
            output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();

        }
        catch
        {
            return null;
        }

        // pattern to get all connections
        var pattern = @"(?xis) 
(?<Header>
     (\r|\n) [^\r]+ :  \r\n\r\n
)
(?<content>
    .+? (?= ( (\r\n\r\n)|($)) )
)";

        List<Match> matches = new List<Match>();

        foreach (Match m in Regex.Matches(output, pattern))
            matches.Add(m);

        var connection = matches.Select(m => new
        {
            containsIp = m.Value.Contains(ipAddress),
            containsPhysicalAddress = Regex.Match(m.Value, @"(?ix)Physical \s Address").Success,
            content = m.Value
        }).Where(x => x.containsIp && x.containsPhysicalAddress)
        .Select(m => Regex.Match(m.content, @"(?ix)  Physical \s address [^:]+ : \s* (?<Mac>[^\s]+)").Groups["Mac"].Value).FirstOrDefault();

        return connection;
    }

Because if I'm using, for example, Chinese version of Windows, the Regex will not work! 因为,例如,如果我使用的是中文版本的Windows,则正则表达式将无法正常工作!

Here is a proposed solution that does what you are asking for: 这是一个建议的解决方案,可以满足您的要求:

void Main()
{
    Console.WriteLine(GetMacByIP("192.168.15.161")); // will return "00-E2-4C-98-18-89"
}

public string GetMacByIP(string ipAddress)
{
    // grab all online interfaces
    var query = NetworkInterface.GetAllNetworkInterfaces()
        .Where(n =>
            n.OperationalStatus == OperationalStatus.Up && // only grabbing what's online
            n.NetworkInterfaceType != NetworkInterfaceType.Loopback)
        .Select(_ => new
        {
            PhysicalAddress = _.GetPhysicalAddress(),
            IPProperties = _.GetIPProperties(),
        });

    // grab the first interface that has a unicast address that matches your search string
    var mac = query
        .Where(q => q.IPProperties.UnicastAddresses
            .Any(ua => ua.Address.ToString() == ipAddress))
        .FirstOrDefault()
        .PhysicalAddress;

    // return the mac address with formatting (eg "00-00-00-00-00-00")
    return String.Join("-", mac.GetAddressBytes().Select(b => b.ToString("X2")));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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