Getting a MAC Address with ASP.NET 4.0 and C#
Adding the Default.aspx Page
To view the MAC address we will be getting, we will need a simple web site that will allow us to display some data. At this point, I have created a new ASP.NET Empty Web Site and need to add in a Web Form with a label. To do this:
- Right click the project in your Solution Explorer.
- Select Add New Item…
- Select a Web Form.
- Name it Default.aspx.
- Click Add.
- Open Default.aspx up to Design mode.
- Drag and drop a Label onto the Web Form.
Getting the MAC Address in C#
Next, we need to add some code that will grab the MAC address from the current computer and display it on the web page. To do this:
1. Open Default.ASPX.CS up for editing.
2. At the top of the class add the following using statement:
3: In the Page_Load event method add in the following code:
protected void Page_Load(object sender, EventArgs e)
//get all nics
NetworkInterface nics = NetworkInterface.GetAllNetworkInterfaces();
//display the physical address of the first nic in the array,
//which should correspond to our mac address
Label1.Text = nics.GetPhysicalAddress().ToString();
Let’s review what this code is actually doing. First, we create an array of NetworkInterface objects and then populate that using the GetAllNetworkInterfaces method. Then, we display the physical or MAC address of the first NetworkInterface in the array which will correspond to your MAC address. Depending on your hardware you may want to use a different index of the array, however this will suffice for most machines.