【发布时间】:2012-05-15 17:40:28
【问题描述】:
我使用此代码获取公共 IP 地址(感谢此帖子 How to get the IP address of the server on which my C# application is running on?):
public static string GetPublicIP()
{
try
{
String direction = "";
WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
using (WebResponse response = request.GetResponse())
{
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
direction = stream.ReadToEnd();
}
}
//Search for the ip in the html
int first = direction.IndexOf("Address: ") + 9;
int last = direction.LastIndexOf("</body>");
direction = direction.Substring(first, last - first);
return direction;
}
catch (Exception ex)
{
return "127.0.0.1";
}
}
但是无论谁访问我的网站,他们都获得相同的IP,并且是服务器公共IP,而不是当前用户的IP。
是否可以在当前用户的上下文中运行 WebRequest,而不是作为服务器?
或者是我在 App_Code 中运行这个函数导致当前用户请求不可用,而是使用服务器上下文的问题?
请帮忙!
【问题讨论】:
-
网站调用/请求是从您的服务器发生的。这意味着在运行此代码的服务器发送的 HTTP 数据包中,它将包含您的服务器 ipaddress。因此,如果您想要客户的 IP 地址,那么您为什么要请求其他网站?只需打开来自客户端的 http 数据包。希望我对您的问题的理解是正确的。 :O
-
猜你是对的,但如果我使用 ex,我不会得到正确的 IP。 Request.ServerVariables["REMOTE_ADDR"]。然后我得到我的本地 VPN IP,而不是我使用 checkip.dyndns.org 时得到的公共 IP。
-
如果涉及 VPN,您想要的可能无法实现。您能否举例说明您在特定情况下会发生什么?
-
我假设您已经运行了一个 Web 服务。您必须让 WCF 托管您的服务。我想我不确定你的端到端故事是什么。您可以通过此tutorial 开始使用 WCF 服务
-
是否有任何商业图书馆或可用的东西? checkip.dyndns.org 如何提供正确的地址?