简体   繁体   English

获取用户 ip 地址 C# ASP.NET 网络表单

[英]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.我正在尝试获取任何用户用于访问我的网站的 ip 地址,但我得到的是托管我的网站的 web 托管公司的服务器/机器的 ip 地址。 I'm trying to save the ip address of the users and administrator as well for the activity logs.我正在尝试保存用户和管理员的 ip 地址以及活动日志。

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:和截图:

这是我的活动日志的图像

The standard Request.UserHostAddress only captures the IP address of the proxy server or router of the user.标准的 Request.UserHostAddress 仅捕获用户的代理服务器或路由器的 IP 地址。 When this is the case the user's IP address is stored in the server variable HTTP_X_FORWARDED_FOR .在这种情况下,用户的 IP 地址存储在服务器变量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所以我们要做的是首先检查HTTP_X_FORWARDED_FOR ,如果它是空的,我们就简单地返回 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/阅读HTTP_X_FORWARDED_FORhttps://www.jamescrowley.net/2007/06/19/gotcha-http-x-forwarded-for-returns-multiple-ip-addresses/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM