【问题标题】:How to Get Client IP Address using Asp.Net C# - When our Project is Hosted in IIS如何使用 Asp.Net C# 获取客户端 IP 地址 - 当我们的项目托管在 IIS 中时
【发布时间】:2017-04-29 11:46:12
【问题描述】:

我在 asp.net c# 中工作,因为我需要获取客户端 IP 地址来显示客户端 IP。 我在 IIS 7 中托管我的项目,使用静态 ip 我可以连接我的应用程序..

我必须使用以下代码获取客户端 IP。但我无法获得正确的 IP 地址..

每次我得到这个ip 192.168.1.18..

我使用以下代码

private void GetIP()
    {
       string userip = Request.UserHostAddress;
        if (Request.UserHostAddress != null)
        {
            Int64 macinfo = new Int64();
            string macsrc = macinfo.ToString("X");
            if (macsrc == "0")
            {
                if (userip == "127.0.0.1")
                {
                    //ScriptManager.RegisterStartupScript(this, GetType(), "Message", "alert('Visited Localhost')", true);
                    lblIPAddress.Text = userip;
                }
                else
                {
                    lblIPAddress.Text = userip;
                }
            }
        }            
    }

我也在使用以下代码,但它显示了托管的 IP 地址,例如 192.168.1.5,我在服务器中托管我的项目..

public static string GetLocalIPAddress()
    {
        var host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (var ip in host.AddressList)
        {
            //if (ip.AddressFamily == AddressFamily.InterNetwork)
            if (ip.AddressFamily != AddressFamily.InterNetworkV6)
            {
                return ip.ToString();
            }
        }
        throw new Exception("Local IP Address Not Found!");
    }

我需要正确的客户端IP地址,任何人帮助

【问题讨论】:

标签: c# asp.net ip client ip-address


【解决方案1】:

试试这个:

字符串 IP = Request.UserHostAddress;

【讨论】:

    【解决方案2】:

    前段时间回答了,但这里有一个类似的问题 How to Get IP Address? 使用 HTTP_X_FORWARDED_FOR 和 REMOTE_ADDR 请求变量。我们最近在一个项目中使用了它,它运行良好

    【讨论】:

    • 先生,当您托管在云中时它工作正常,但是当我们托管在我们自己的服务器(即 IIS)中时它无法正常工作..所以我需要帮助先生..
    • 我们在 IIS 服务器上使用了它,它仍然可以正常工作
    • 先生,我又检查了一遍,它也显示像这样 192.168.1.18
    • @Surya 你可以尝试阅读这个stackoverflow.com/questions/6914457/… 他们似乎有同样的问题,
    • 执行项目时显示 127.0.0.1,但托管时显示 192.168.1.18..
    猜你喜欢
    • 2021-07-18
    • 2014-02-21
    • 2015-04-24
    • 2011-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-21
    相关资源
    最近更新 更多