Get the visitors IP address in ASP.NET

This article helps you to know how to get the IP address of visitors to your site in ASP.NET.
  • 5725

Every visitor to your site or web application has an IP address and many times you want to get it for the purpose of security logging, or perhaps tracing. This article helps you to know how to get the IP address of visitors of your site.

As you know that when users are behind any routers or proxies the REMOTE_ADDR returns the IP Address of the router and not the client user's machine. Hence first of all we have to check HTTP_X_FORWARDED_FOR, since when client user is behind a proxy server its machine's IP Address and Proxy Server's IP Address is appended to the client machine's IP Address. So, we need to check HTTP_X_FORWARDED_FOR and then REMOTE_ADDR.

Lets see the code snippets to get the visitors IP address.

 

Default.aspx

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="IP_Address" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <title>Example</title>
</head>
<
body>
  <form id="form1" runat="server">
 
   <div>
 
    <asp:TextBox ID="txtIPAddress" runat="server" Width="205px"></asp:TextBox
 
   </div>
  </
form>
</body>
</
html>

Default.aspx.vb 

Partial Class IP_Address
  Inherits System.Web.UI.Page
  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
     Dim nowip As String
     nowip = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
     If nowip = "" Then
       nowip = Request.ServerVariables("REMOTE_ADDR")
     End If
     If txtIPAddress.Text = "" Then
       txtIPAddress.Text = nowip
     End If
  End Sub
End Class

Run the above code and you will get IP address of the visitor to your site.

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.