C# 如何在Web服务C中获取客户机的internet地址#
我需要asp.net web服务中的客户端计算机internet IP地址,我正在使用以下代码C# 如何在Web服务C中获取客户机的internet地址#,c#,.net,web-services,C#,.net,Web Services,我需要asp.net web服务中的客户端计算机internet IP地址,我正在使用以下代码 string IPaddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (string.IsNullOrEmpty(IPaddress)) IPaddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; i
string IPaddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(IPaddress))
IPaddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (string.IsNullOrEmpty(IPaddress))
IPaddress = HttpContext.Current.Request.UserHostAddress;
但是这里我得到了客户端机器的本地IP,但是我正在寻找客户端机器的公共IP/互联网IP*
请帮助我,任何人。请求有两个属性提供客户端IP地址。 代码如下:
private string GetClientIpAddress (HttpRequestMessage request)
{
if ( request.Properties.ContainsKey("MS_HttpContext") )
{
return ((HttpContextWrapper) request.Properties["MS_HttpContext"]).Request.UserHostAddress;
}
if ( request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name) )
{
var prop = (RemoteEndpointMessageProperty) request.Properties[RemoteEndpointMessageProperty.Name];
return prop.Address;
}
if ( request.Headers.Contains("X-Forwarded-For") )
{
return request.Headers.GetValues("X-Forwarded-For").FirstOrDefault();
}
// Self-hosting using Owin. Add below code if you are using Owin communication listener
if ( request.Properties.ContainsKey("MS_OwinContext") )
{
var owinContext = (OwinContext) request.Properties["MS_OwinContext"];
if ( owinContext?.Request != null )
{
return owinContext.Request.RemoteIpAddress;
}
}
if ( HttpContext.Current != null )
{
return HttpContext.Current.Request.UserHostAddress;
}
return null;
}
希望它能起作用。
~Prasad您可以获得客户端连接到服务器的连接的IP地址。如果这是在同一个网络中,您将看不到公共IP地址,因为连接没有通过internet路由。@它工作了吗?如果没有,请告诉我们获取客户端IP地址的正确方法~普拉萨德