Sponser Link

How to count visitors on website in asp.net c#

In website, it is very necessary to know the no of visitors in our website. Therefore I will explain in this article that how we can count the visitors and record the IP address of users.

Now go to in Global.asax file and write the function for get the IP address of client.

protected string GetIPAddress()

{

  System.Web.HttpContext context = System.Web.HttpContext.Current;

  string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

  if (!string.IsNullOrEmpty(ipAddress))

  {

     string[] addresses = ipAddress.Split(',');

     if (addresses.Length != 0)

     {

       return addresses[0];

     }

  }

  return context.Request.ServerVariables["REMOTE_ADDR"];

}

Now create the table in database for record the IP address.

CREATE TABLE [dbo].[User_IPDetail](

   [SNo] [int] IDENTITY(1,1) NOT NULL,

   [Hit_IPAddress] [nvarchar](50) NULL,

   [Hit_Time] [datetime] NULL,

   [Hit_Date] [datetime] NULL,

) ON [PRIMARY]

Write the event of session start. This event will trigger when new client session will open. On open new session, system will record the IP address in database. You can exact know the no of ip hit count and location of ip after further process on ip data.

protected void Session_Start(object sender, EventArgs e)

{

   string qry = "";

   string ConnString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;

   SqlConnection sqlconn = new SqlConnection(ConnString);

   SqlCommand sqlcmd = new SqlCommand();

   sqlcmd.CommandType = CommandType.Text;

   DateTime dt = DateTime.Now;

   qry = "Insert into [User_IPDetail_CODE] (Hit_IPAddress,Hit_Time,Hit_Date)

   Values('" + GetIPAddress() + "',getdate(),'" + dt.ToString("yyyy-MM-dd") + "')";

   sqlcmd.CommandText = qry;

   sqlcmd.Connection = sqlconn;

   sqlconn.Open();

   sqlcmd.ExecuteNonQuery();

   sqlconn.Close();

}