2

我使用此代码获取公共 IP 地址(感谢这篇文章如何获取运行我的 C# 应用程序的服务器的 IP 地址?):

    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 中运行此函数以使当前用户请求不可用,而是使用服务器上下文的问题?

请帮忙!

4

3 回答 3

0

我猜这段代码是在网络服务器上运行的——你有一个页面可以让客户检查他们的 IP 地址吗?如果是这样,我怀疑你已经糊涂了。如果没有,请详细说明它在哪里运行。

如果上面的代码在服务器运行,那么如果您调用远程服务器并询问“此请求来自哪个 IP 地址”,您将始终获得该服​​务器的公共 IP 地址 - 这就是您的代码示例正在做。

如果您想要呼叫您的客户端的 IP 地址 - 假设您是一个 Web 应用程序,那么您应该查看HttpWebRequest.UserHostAddress,尽管请注意这不是万无一失的。在这里查看更多信息。

于 2012-05-15T09:24:35.520 回答
0

这应该会发生,代码正在您的机器上运行,因此您可以获得自己的 IP 地址。要从用户那里获取信息,您必须检查用户发送的标头,特别是REMOTE_ADDR标头。

您可能可以在代码中的某处使用Request.ServerVariables["REMOTE_ADDR"]

于 2012-05-15T09:25:37.327 回答
0

由于您是从服务器发出请求,因此您将获得服务器的 IP 地址。

我不确定你有什么样的服务。对于 WCF 服务,您可以从请求的 OperationContext 对象的 IncomingMessageProperties 中获取 IP 地址。在此处查看示例:Get the Client's Address in WCF

[ServiceContract]
public interface IMyService
{
    [OperationContract]
    string GetAddressAsString();
}

public class MyService : IMyService
{
    public string GetAddressAsString()
    {
        RemoteEndpointMessageProperty clientEndpoint =
            OperationContext.Current.IncomingMessageProperties[
            RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;

        return String.Format(
            "{0}:{1}",
            clientEndpoint.Address, clientEndpoint.Port);
    }
}
于 2012-05-15T09:31:04.217 回答