Article

How to get IP Address and MAC Address in Asp.net using C#

10 Jun 2015 Kamal Pratap
0 Comments 1748 Views
C#



Sometimes we need to get Machine Identity to perform some task. Here we explain the C# code to display the IP Address and MAc Address. You can

Asp.Net :

  Host Name :  <asp:Label ID="lblHostName" runat="server" ></asp:Label><br />
  IP Address :  <asp:Label ID="lblIPAddress" runat="server" ></asp:Label><br />
  MAC Address :  <asp:Label ID="lblMacAddress" runat="server" ></asp:Label><br />

C# :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.NetworkInformation;

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Get_IP();
        Get_MAC();
    }
    protected void Get_IP()
    {
        string HostName = Dns.GetHostName(); // Retrive the Name of HOST
        lblHostName.Text = HostName;
        string IPAddress = Dns.GetHostByName(HostName).AddressList[0].ToString(); // Get the IP
        lblIPAddress.Text = IPAddress;       
    }
    protected void Get_MAC()
    {
        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();  //get mac address
            }
        }
        lblMacAddress.Text = sMacAddress;
    }
}

 

Kamal Pratap

I have 6+ years experience in .Net technologies like Asp.Net, C#, WCF, Web Services, SQL Server, Ajax, LinQ. Currently I am working in Netcarrots Loyalty Services as a Software Developer.

Comments

No coments found to display!

Leave a Comment