Saturday, August 14, 2010

♦ C# get mac address

Figure 1: Output Screen, MAC Address list at Local Machine

Our computer have a physical address 48 bytes size ()
00-12-3F-B1-17-A5           is Ethernet adapter Local Area Connection.
00-00-00-00-00-00-00-E0  is Tunnel adapter isatap (Microsoft ISATAP Adapter)
00-00-00-00-00-00-00-E0  is Tunnel adapter Local Area Connection* 9
                                          (Microsoft Teredo Tunneling Adapter)
if you want to know your PC mac address you can use command line
          c:\windows>ipconfig /all          [Enter]

you will found all your interface and your Network Interface Card (NIC) informations.

this program use  c# Class and method below.
      Namespace "System.Net.NetworkInformation"
      Class          "NetworkInterface"
      Method       "GetAllNetworkInterfaces()"
      Method       "GetPhysicalAddress()"

      Class           "PhysicalAddress"
      Method       "GetAddressBytes()"

Example Program:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Net.NetworkInformation;

namespace getmac
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
           NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            if (nics == null || nics.Length < 1)
            {
                textBox1.Text = "No network interfaces found.";
                return;
            }
        
            foreach (NetworkInterface adapter in nics)
            {
                PhysicalAddress address = adapter.GetPhysicalAddress();
                byte[] bytes = address.GetAddressBytes();

                for (int i = 0; i < bytes.Length; i++)
                {
                    textBox1.Text += bytes[i].ToString("X2"); // display in HEX

                    // Insert a hyphen after each byte, unless we are at the end of the 
                    if (i != bytes.Length - 1)
                    {
                        textBox1.Text += "-";
                    }
                }
                textBox1.Text += Environment.NewLine;
            }

         }
    }
}


if you did not understand "foreach loopread this where describe the easy your understand and use its.

Example Program: without foreach..loop

private void button1_Click(object sender, EventArgs e)
{
   NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
   int num_nics=nics.Length;
   for (int i=0; i< num_nics; i++)
   {
      PhysicalAddress mac = nics[i].GetPhysicalAddress();
      textBox1.Text += mac.ToString();
      textBox1.Text += Environment.NewLine;
   }
}

The result this program same with above but no-insert a hyphen after each byte.


and  http://msdn.microsoft.com/en-us/library/z1d0eff3.aspx for more useful method.

No comments:

Post a Comment