Sunday, January 18, 2009

How To Track IP In ASP.net C#

You can use this piece of code to track the ip addresses of users who visit your web site
effectively.




using System.Configuration;
using System.Net;
using System.IO;


protected string TrackIP()
{

// Track Visitors

string ipAddress = IpAddress();

//To get the host name
//string hostName = Dns.GetHostByAddres(ipAddress).HostName;


//To add a log file
/*string hostName = "My Host";

StreamWriter wrtr = new StreamWriter(Server.MapPath("\\Log\\visitors.log"), true);

wrtr.WriteLine(DateTime.Now.ToString() + " | " + ipAddress + " | " + hostName + " | " + Request.Url.ToString());

wrtr.Close();*/

return ipAddress;
}

private string IpAddress()
{

string strIpAddress;

strIpAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

if (strIpAddress == null)

strIpAddress = Request.ServerVariables["REMOTE_ADDR"];//Get remote IP address

return strIpAddress;

}

No comments: