How To Get User's IP Address in Asp.Net using C#, VB.Net

In this tutorial i am going to share with you how to get users / client ip address in Asp.Net using both C# and VB.Net or also retrieving user's ip address in asp.net using c# and vb.net or how to get ip addres of visitors machine / system in asp.net using c# and vb.net with example.

So, let's take one example for demonstration purpose.

To get ip address of user/client/visitor's machine/system you need to create one web application and also need to create one web page within website directory and write following aspx code in that created web page.

aspx code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <b>Your Ip Address is :</b>
        <asp:Label ID="lbl_ip" ForeColor="Blue" Font-Bold="true" Font-Size="XX-Large" runat="server"></asp:Label>
        <br />
        <br />
        <asp:Button ID="btn_Getip" runat="server" Text="Get IP Address" OnClick="btn_Getip_Click" />
    </div>
    </form>
</body>
</html>

C# Code to Get User's IP Address

protected void btn_Getip_Click(object sender, EventArgs e)
   {
       string IPAddress = string.Empty;
       IPAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
       if (string.IsNullOrEmpty(IPAddress))
           IPAddress = Request.ServerVariables["REMOTE_ADDR"];
       lbl_ip.Text = IPAddress;
   }

Vb.Net Code to Get User's IP Address

Protected Sub btn_Getip_Click(sender As Object, e As EventArgsHandles btn_Getip.Click
        Dim IPAddress As String = String.Empty
        IPAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
        If String.IsNullOrEmpty(IPAddress) Then
            IPAddress = Request.ServerVariables("REMOTE_ADDR")
        End If
        lbl_ip.Text = IPAddress
    End Sub

Demo:

Get User's IP Address in Asp.Net

Previous
Next Post »

If you have any kind of question about any post, Feel free to ask.You can simply drop a comment below post. Your feedback and suggestions will be highly appreciated. ConversionConversion EmoticonEmoticon