How to get Client IP Address in Asp.net

Description:-

In this Example we see how to get Client IP Address in dot net. We will use IPHostEntry Class for Getting Client IP Address when come in any site to get IP Address we will create method for getting IP Address. Using Dns Class through we will get Hostname and using this we will get Client IP Address. IPAddress is the Address of Client PC. 

The "IP" part of IP address stands for "Internet Protocol." The "address" part refers to a unique number that gets linked to all online activity you do...somewhat like a return address on a letter you'd send out.

An IP address is a fascinating product of modern computer technology designed to allow one computer (or other digital device) to communicate with another via the Internet. IP addresses allow the location of literally billions of digital devices that are connected to the Internet to be pinpointed and differentiated from other devices. In the same sense that someone needs your mailing address to send you a letter, a remote computer needs your IP address to communicate with your computer.

An IP address consists of four numbers, each of which contains one to three digits, with a single dot (.) separating each number or set of digits. Each of the four numbers can range from 0 to 255.

Your IP address is something you probably rarely think about, but it's vitally important to your online lifestyle. Without an IP address, you wouldn't be able to get today's weather, check the latest news or look at videos online. So we can Store our client IPAddress we he/she visits our Site or Application.

So let’s start and get Client IPAddress using dot net. Create Webpage and Drag button Control to get IP.

Html Code:-

<div>
   <table>
      <tr>
         <td>
            <asp:Button ID="btnClick" runat="server" Text="Get IPAddress" Height="35px" Width="105px" OnClick="btnClick_Click" />
         </td>
      </tr>
      <tr>
         <td>
            <asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Size="X-Large" Text=""></asp:Label>
         </td>
      </tr>
   </table>
</div>

Now go to Code behind and Create Code for getting IPAddress of Client.

protected void btnClick_Click(object sender, EventArgs e)
{
    Label1.Text = GetIpAddress() + ", HostName is "+ GetCompCode();
}

public static string GetIpAddress()// Get IP Address
{
    string ip = "";
    IPHostEntry ipEntry = Dns.GetHostEntry(GetCompCode());
    IPAddress[] addr = ipEntry.AddressList;
    ip = addr[1].ToString();
    return ip;
}

public static string GetCompCode()// Get Computer Name
{
    string strHostName = "";
    strHostName = Dns.GetHostName();
    return strHostName;
}

Now run your Webpage and Click on Button you will get IPAddress or Host name. 

Related Posts

Previous
Next Post »

Thanks for comments.....