获取客户端IP NOT Web服务器IP

时间:2014-11-07 12:06:31

标签: c# asp.net webrequest

public static string GetPublicIp()
    {
        string direction = "";
        WebRequest request = WebRequest.Create("http://checkip.dyndns.org");
        using (WebResponse response1 = request.GetResponse())
        using (StreamReader stream1 = new StreamReader(response1.GetResponseStream()))
        {
            direction = stream1.ReadToEnd();
        }
        //Search for the ip in the html
        int first1 = direction.IndexOf("Address: ") + 9;
        int last1 = direction.LastIndexOf("</body>");
        direction = direction.Substring(first1, last1 - first1);

        return direction;
    }

我试图在加载asp.net页面时获取客户端IP。我尝试使用checkip.dyndns.org服务,如上面的代码片段所示,但它返回托管ASP.NET应用程序的Web服务器的IP。

有没有我可以修改该代码并让它返回客户端公共IP? (我需要他们的公共IP,而不是他们的本地IP )或者他们是如何返回客户端公共IP(不是Web服务器IP)的更好的例子

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容:

var userIpAddress = HttpContext.Current.Request.UserHostAddress;
相关问题