0

我正在使用我在Get public IP using DynDNS and WebRequest C#中找到的这段代码

获取 IP 地址。但我只是从服务器获取 IP 地址,而我需要的是来自连接到我的 Web 应用程序的用户的 IP 地址。

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);
4

2 回答 2

2

如果您正在运行 Web 应用程序,并且想要您的“客户端”IP,则需要使用 UserHostAddress

var userAddress = HttpContext.Current.Request.UserHostAddress;
于 2012-06-01T14:42:05.260 回答
0

首先获取上下文:

HttpListenerContext ctx = m_HttpListener.GetContext();

接受请求后,客户端信息可在ctx. 用于ctx获取客户端 IP 地址:

string IP = ctx.Request.RemoteEndPoint.Address.ToString();
于 2013-02-12T05:58:15.690 回答