How do I obtain the physical (MAC) address of an IP address using C#?

后端 未结 4 1407
失恋的感觉
失恋的感觉 2020-12-05 20:03

From C#, I want to do the equivalent of the following:

arp -a |findstr 192.168.1.254

Alternatively, the answer could call the SendARP funct

4条回答
  •  没有蜡笔的小新
    2020-12-05 20:41

    Here is my solution.

    public static class MacResolver
    {
        /// 
        /// Convert a string into Int32  
        /// 
        [DllImport("Ws2_32.dll")]
        private static extern Int32 inet_addr(string ip);
    
        /// 
        /// The main funtion 
        ///  
        [DllImport("Iphlpapi.dll")]
        private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 len);
    
        /// 
        /// Returns the MACAddress by a string.
        /// 
        public static Int64 GetRemoteMAC(string remoteIP)
        {   
            Int32 ldest = inet_addr(remoteIP);
    
            try
            {
                Int64 macinfo = 0;           
                Int32 len = 6;           
    
                int res = SendARP(ldest, 0, ref macinfo, ref len);
    
                return macinfo;    
            }
            catch (Exception e)
            {
                return 0;
            }
        }
    
        /// 
        /// Format a long/Int64 into string.   
        /// 
        public static string FormatMac(this Int64 mac, char separator)
        {
            if (mac <= 0)
                return "00-00-00-00-00-00";
    
            char[] oldmac = Convert.ToString(mac, 16).PadLeft(12, '0').ToCharArray();
    
            System.Text.StringBuilder newMac = new System.Text.StringBuilder(17);
    
            if (oldmac.Length < 12)
                return "00-00-00-00-00-00";
    
            newMac.Append(oldmac[10]);
            newMac.Append(oldmac[11]);
            newMac.Append(separator);
            newMac.Append(oldmac[8]);
            newMac.Append(oldmac[9]);
            newMac.Append(separator);
            newMac.Append(oldmac[6]);
            newMac.Append(oldmac[7]);
            newMac.Append(separator);
            newMac.Append(oldmac[4]);
            newMac.Append(oldmac[5]);
            newMac.Append(separator);
            newMac.Append(oldmac[2]);
            newMac.Append(oldmac[3]);
            newMac.Append(separator);
            newMac.Append(oldmac[0]);
            newMac.Append(oldmac[1]);
    
            return newMac.ToString();
        }
    }
    

提交回复
热议问题