Tuesday 14 April 2015

How to get client MAC address in ASP.NET?


 In this article I will explain how to get the client MAC address in ASP.NET using C#.NET.

We may have a requirement to get Client MAC address. We implemented the blow code for Client MAC address.

Add below namespaces to your aspx.cs page.

using System.Net;
using System.Runtime.InteropServices;
using System.Net.NetworkInformation;


public partial class _Default : Page
{

    [DllImport("Iphlpapi.dll")]
    private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
    [DllImport("Ws2_32.dll")]
    private static extern Int32 inet_addr(string ip);

In the Page_Load event method add in the following code:

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            string userip = Request.UserHostAddress;
            string strClientIP = Request.UserHostAddress.ToString().Trim();
            Int32 ldest = inet_addr(strClientIP);
            Int32 lhost = inet_addr("");
            Int64 macinfo = new Int64();
            Int32 len = 6;
            int res = SendARP(ldest, 0, ref macinfo, ref len);
            string mac_src = macinfo.ToString("X");
          
            while (mac_src.Length < 12)
            {
                mac_src = mac_src.Insert(0, "0");
            }

            string mac_dest = "";

            for (int i = 0; i < 11; i++)
            {
                if (0 == (i % 2))
                {
                    if (i == 10)
                    {
                        mac_dest = mac_dest.Insert(0, mac_src.Substring(i, 2));
                    }
                    else
                    {
                        mac_dest = "-" + mac_dest.Insert(0, mac_src.Substring(i, 2));
                    }
                }
            }

            Response.Write(MAC address is" + mac_dest + "."

             + "<br>");
        }
        catch (Exception err)
        {
            Response.Write(err.Message);
        }
    }

}


1 comment: