3 راه برای بدست آوردن MAC address کارت شبکه به وسیله C#

 

First way:

 

You need to import the System.Net namespace for this to work. This will support IPv4 and IPv6.

 

public string GetMACAddress()

{

    NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();

    String sMacAddress = string.Empty;

    foreach (NetworkInterface adapter in nics)

    {

        if (sMacAddress == String.Empty)// only return MAC Address from first card 

        {

            IPInterfaceProperties properties = adapter.GetIPProperties();

            sMacAddress = adapter.GetPhysicalAddress().ToString();

        }

    } return sMacAddress;

}

 

Second way:

 

To implement this function you need to add System.Management namespace in your application. If it is not available you need to add its reference from "Add references" from your project. 

 

public string GetMACAddress()

{

    ManagementObjectSearcher objMOS = new ManagementObjectSearcher("Win32_NetworkAdapterConfiguration");

    ManagementObjectCollection objMOC = objMOS.Get();

    string MACAddress = String.Empty;

    foreach (ManagementObject objMO in objMOC)

    {

        if (MACAddress == String.Empty) // only return MAC Address from first card  

        {

            MACAddress = objMO["MacAddress"].ToString();

        }

        objMO.Dispose();

    }

    MACAddress = MACAddress.Replace(":", "");

    return MACAddress;

}

 

You might want to also add  "objMO ["Caption"].ToString()" to test before the mac address so that you know which devices you are looking at. 

 

Also, don't forget to use try/catch blocks on these as a NullPointerReference will kill the app.

 

How to get Client MAC address(Web):

 

To get the client MAC address only way we can rely on JavaScript and Active X control of Microsoft.It is only work in IE if Active X enable for IE. As the ActiveXObject is not available with the Firefox, its not working with the firefox and is working fine in IE.

 

This script is for IE only:

 

<script language="javascript" type="text/javascript">

    function showMacAddress() {

        var obj = new ActiveXObject("WbemScripting.SWbemLocator");

        var s = obj.ConnectServer(".");

        var properties = s.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration");

        var e = new Enumerator(properties);

        var output;

        output = '

';

        output = output + '

';

        while (!e.atEnd()) {

            e.moveNext();

            var p = e.item();

            if (!p) continue;

            output = output + '

';

            output = output + '

';

            output = output + '

';

            output = output + '

';

        }

        output = output + '

CaptionMACAddress
' + p.Caption; +' ' + p.MACAddress + '
';

        document.getElementById("box").innerHTML = output;

    }

script>