Monday, November 11, 2013

How to get client IP address in asp.net

We can get client IP address who visited out website in asp.net in c# and vb.net. To implement this sample code as shown below

Default.aspx

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>Get visitors client IP in asp.net</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:Label ID="labelIP" runat="server" Font-Bold="true"/>

</div>

</form>

</body>

</html> 

Now write the following code in code behind

C# Code


protected void Page_Load(object sender, EventArgs e)

{

string IPAdd = string.Empty;

IPAdd = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

if (string.IsNullOrEmpty(IPAdd))

IPAdd = Request.ServerVariables["REMOTE_ADDR"];

lblIP.Text = IPAdd;

}

VB.NET Code


Partial Class Default

Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

Dim IPAdd As String = String.Empty

IPAdd = Request.ServerVariables("HTTP_X_FORWARDED_FOR")

If String.IsNullOrEmpty(IPAdd) Then

IPAdd = Request.ServerVariables("REMOTE_ADDR")

End If

lblIP.Text = IPAdd

End Sub

End Class 

If you observe above code when users behind any proxies or routers the REMOTE_ADDR returns the IP Address of the router and not the client user's machine. Hence first we need to check HTTP_X_FORWARDED_FOR, since when client user is behind a proxy server his machine's IP Address the Proxy Server's IP Address is appended to the client machine's IP Address.

If you are searching life partner. your searching end with kpmarriage.com. now kpmarriage.com offer free matrimonial website which offer free message, free chat, free view contact information. so register here : kpmarriage.com- Free matrimonial website