如何在 C# 中从用户客户端获取 IP 地址
本文关键字:客户端 获取 IP 地址 用户 | 更新日期: 2023-09-27 18:35:57
我正在使用我在使用 DynDNS 和 WebRequest C# 获取公共 IP 中找到的这段代码
以获取 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);
如果您正在运行 Web 应用程序,并且想要"客户端"的 IP,则需要使用 UserHostAddress。
var userAddress = HttpContext.Current.Request.UserHostAddress;
首先获取上下文:
HttpListenerContext ctx = m_HttpListener.GetContext();
接受要求后,客户端信息在ctx
中可用。使用 ctx
获取客户端 IP 地址:
string IP = ctx.Request.RemoteEndPoint.Address.ToString();