繁体   English   中英

如何从C#中的用户客户端获取IP地址?

[英]How can I get the IP address from the user client in C#?

我正在使用我在使用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();

在接受resetset之后,客户端信息可以在ctx 使用ctx获取客户端IP地址:

string IP = ctx.Request.RemoteEndPoint.Address.ToString();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM