Yvonne
Yvonne

Reputation: 41

Getting user ip address C# ASP.NET webforms

I'm trying to get the ip address of any user uses to access my site but instead I get the ip address of the server/machine of the web hosting company that is hosting my site. I'm trying to save the ip address of the users and administrator as well for the activity logs.

This is the code I'm using:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Payments
{
    public partial class AdministratorLogin : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Session["administratorloggedin"] = false;
        }

        protected void login_Click(object sender, EventArgs e)
        {
            string s = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

            using (SqlConnection conn = new SqlConnection(s))
            {
                SqlCommand cmd = new SqlCommand("select * from AdministratorP where AdministratorId = @AdministratorId and Password = @Password", conn);
                cmd.Parameters.AddWithValue("@AdministratorId", administratorid.Text);
                cmd.Parameters.AddWithValue("@Password", password.Value);

                SqlDataAdapter sda = new SqlDataAdapter(cmd);

                DataTable dt = new DataTable();
                sda.Fill(dt);

                conn.Open();
                int i = cmd.ExecuteNonQuery();
                
                if (dt.Rows.Count > 0)
                {
                    if (captcha.Text.ToLower() == Session["CaptchaVerify"].ToString())
                    {
                        Session["administratorloggedin"] = true;
                        Session["AdministratorId"] = this.administratorid.Text.Trim();

                        SqlCommand cmd_al = new SqlCommand("spAdministratorActivityLogP", conn);
                        cmd_al.CommandType = CommandType.StoredProcedure;
                        cmd_al.Parameters.AddWithValue("@AdministratorId", administratorid.Text);
                        cmd_al.Parameters.AddWithValue("@DateTimestamp", DateTime.Now.ToLocalTime());
                        cmd_al.Parameters.AddWithValue("@Action", "Logged in");

                        string hostname = Dns.GetHostName();
                        string ipaddress;

                        ipaddress = Request.UserHostAddress;

                        if (string.IsNullOrEmpty(ipaddress))
                        {
                            ipaddress = Request.UserHostAddress;
                        }

                        cmd_al.Parameters.AddWithValue("@HostName", hostname);
                        cmd_al.Parameters.AddWithValue("@IPAddress", ipaddress);

                        cmd_al.ExecuteNonQuery();
                        conn.Close();

                        Server.Transfer("AdministratorPage.aspx");
                    }
                    else
                    {
                        Response.Write("<script> alert('Captcha code incorrect')</script>");
                    }
                }
                else
                {
                    Response.Write("<script> alert('Administrator Id or Password incorrect')</script>");
                }
            }
        }
    }
}

And a screenshot:

This is an image of my activity log

Upvotes: 0

Views: 925

Answers (1)

Phani
Phani

Reputation: 861

The standard Request.UserHostAddress only captures the IP address of the proxy server or router of the user. When this is the case the user's IP address is stored in the server variable HTTP_X_FORWARDED_FOR.

So what we want to do is first check HTTP_X_FORWARDED_FOR and if that is empty we then simply return ServerVariable REMOTE_ADDR

Try this:

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"];
}

Read up on HTTP_X_FORWARDED_FOR : https://www.jamescrowley.net/2007/06/19/gotcha-http-x-forwarded-for-returns-multiple-ip-addresses/

Upvotes: 1

Related Questions