Get a machines MAC address on the local network from its IP in C#

后端 未结 4 794
情深已故
情深已故 2020-12-09 05:34

I am trying write a function that takes a single IP address as a parameter and queries that machine on my local network for it\'s MAC address.

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-09 05:57

    Just a better performing version of the accepted method.

        public string GetMacByIp( string ip )
        {
            var pairs = this.GetMacIpPairs();
    
            foreach( var pair in pairs )
            {
                if( pair.IpAddress == ip )
                    return pair.MacAddress;
            }
    
            throw new Exception( $"Can't retrieve mac address from ip: {ip}" );
        }
    
        public IEnumerable GetMacIpPairs()
        {
            System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
            pProcess.StartInfo.FileName = "arp";
            pProcess.StartInfo.Arguments = "-a ";
            pProcess.StartInfo.UseShellExecute = false;
            pProcess.StartInfo.RedirectStandardOutput = true;
            pProcess.StartInfo.CreateNoWindow = true;
            pProcess.Start();
    
            string cmdOutput = pProcess.StandardOutput.ReadToEnd();
            string pattern = @"(?([0-9]{1,3}\.?){4})\s*(?([a-f0-9]{2}-?){6})";
    
            foreach( Match m in Regex.Matches( cmdOutput, pattern, RegexOptions.IgnoreCase ) )
            {
                yield return new MacIpPair()
                {
                    MacAddress = m.Groups[ "mac" ].Value,
                    IpAddress = m.Groups[ "ip" ].Value
                };
            }
        }
    
        public struct MacIpPair
        {
            public string MacAddress;
            public string IpAddress;
        }
    

提交回复
热议问题