Link to home
Start Free TrialLog in
Avatar of psft
psftFlag for United States of America

asked on

Get MAC Address from IP in Vista with C# (500pts!)

What I need is C# code that will take an IP Address and return the MAC Address of a remote device.

The code below accomplishes that in XP but not VISTA.  After reading a few articles it seems that the "Iphlpapi.dll" is not the same in Vista as it is in XP.

How can I accomplish this.  Specific examples would be great!
Thanks,

public string GetMacAddress(object response)
        {
            System.Net.IPAddress ip = System.Net.IPAddress.Parse(this.currentIp);
            System.Net.NetworkInformation.PhysicalAddress mac = GetMacFromIP(ip);
 
            //Format MAC Address.
            string macString = mac.ToString();
            for (int i = 2; i < macString.Length; i = i + 3)
            {
               macString = macString.Insert(i, ":");
            }
            return macString;
        }
 
        [System.Runtime.InteropServices.DllImport("Iphlpapi.dll", EntryPoint = "SendARP")]
        internal extern static Int32 SendArp(Int32 destIpAddress, Int32 srcIpAddress, byte[] macAddress, ref Int32 macAddressLength);
 
        
        public static System.Net.NetworkInformation.PhysicalAddress GetMacFromIP(System.Net.IPAddress IP)
        {
            if (IP.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)
                throw new ArgumentException("supports just IPv4 addresses");
 
            Int32 addrInt = IpToInt(IP);
            Int32 srcAddrInt = IpToInt(IP);
            byte[] mac = new byte[6]; // 48 bit    
 
            int length = mac.Length;
            int reply = SendArp(addrInt, srcAddrInt, mac, ref length);
 
            byte[] emptyMac = new byte[12];
 
            if (reply != 0)
            {
                MessageBox.Show("No MAC Address found for IP Address: " + IP.ToString());
                return new System.Net.NetworkInformation.PhysicalAddress(emptyMac);
            }
            return new System.Net.NetworkInformation.PhysicalAddress(mac);
        }
 
        private static Int32 IpToInt(System.Net.IPAddress IP)
        {
            byte[] bytes = IP.GetAddressBytes();
            return BitConverter.ToInt32(bytes, 0);
        }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of dprovencher
dprovencher

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of psft

ASKER

You were right thanks for the insight