简体   繁体   English

获取客户端的公网IP地址

[英]Get the public IP address of a client

I'm creating a web application where I need a functionality that if someone client log in to my website the client's public IP address must be logged. 我正在创建一个Web应用程序,其中需要一个功能,如果有人客户端登录到我的网站,则必须登录该客户端的公共IP地址。 I have some javascript to do this but some of my pal not agree to use a javascript library reason they don't trust it. 我有一些JavaScript可以做到这一点,但是我的一些朋友不同意使用javascript库,因为他们不信任它。 Such as http://l2.io/ip.js?var=myip as mentioned here 如此处提到的 http://l2.io/ip.js?var=myip

So we need all of it as server side code. 因此,我们需要所有这些作为服务器端代码。 So i found few more code in this link but unfortunately I'm not getting the expected result (it only returns local hosts IP). 因此,我在此链接中发现了更多的代码,但是不幸的是我没有得到预期的结果(它仅返回本地主机IP)。 Could anyone help me to solve this please. 谁能帮我解决这个问题。

I have tried the bellow code 我已经尝试过以下代码

string VisitorsIPAddr = string.Empty;
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
    VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
{
    VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
}

but this is not providing me the public IP. 但这没有为我提供公共IP。 Do I need to deploy it or something. 我是否需要部署它或其他东西。

HttpContext.Current.Request.UserHostAddress

This should get the public IP address of a client 这应该获得客户端的公共IP地址

EDIT 编辑

So you're after the IP address of your own machine as the rest of the world sees it?? 所以您在全世界其他地方都在追寻自己计算机的IP地址吗? This only really matters if you're hosting in on lets say an Intranet where the clients will be on the same network and thats the only address you will get if you use HttpContext.Current.Request.UserHostAddress . 仅当您托管在Intranet(客户端将位于同一网络上)上时,这才真正重要,这就是使用HttpContext.Current.Request.UserHostAddress获得的唯一地址。 You will need to use a lookup api or something in this case. 在这种情况下,您将需要使用查找API或其他方法。 But then you'd know the external IP of your network! 但是,您将知道网络的外部IP!

If this is to be hosted on the internet then HttpContext.Current.Request.UserHostAddress will work just fine as every client will be displaying it's external IP. 如果将其托管在Internet上,则HttpContext.Current.Request.UserHostAddress将可以正常工作,因为每个客户端都将显示其外部IP。

It's showing 127.0.0.1 I'm guessing because you're testing on your local machine and this will be it's loopback address. 我正在猜测它显示的是127.0.0.1,因为您正在本地计算机上进行测试,这将是它的回送地址。

Hope this helps 希望这可以帮助

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

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