How To Get Mac Address Of Client Machine In ASP.NET C#

You can only obtain the source IP address of a socket connection made between the client’s machine and the server hosting your website; the MAC address of a user connecting to your website is never communicated via the socket connection.

 

(Client –> Server), to obtain a user’s IP address.

In ASP.NET C#, you may use this code to obtain the client machine’s mac address.

 

public string GetIPAddress()
{
    System.Web.HttpContext context = System.Web.HttpContext.Current;
    string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

    if (!string.IsNullOrEmpty(ipAddress))
    {
        string[] addresses = ipAddress.Split(',');
        if (addresses.Length != 0)
        {
            return addresses[0];
        }
    }

    return context.Request.ServerVariables["REMOTE_ADDR"];
}
[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);

private static string GetClientMAC(string strClientIP)
{
    string mac_dest = "";
    try
    {
        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");
        }

        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));
                }
            }
        }
    }
    catch (Exception err)
    {
        throw new Exception("L?i " + err.Message);
    }
    return mac_dest;
}
protected void Button1_Click1(object sender, EventArgs e)
{
    Label1.Text = GetClientMAC(GetIPAddress());
}

 

Thanks.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories