Reputation: 11
I want Client machine internet IP Address in asp.net web service for that I am using following code
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;
but Here I am getting the client machine local IP But * I am looking public IP/ Internet IP of the client machine*
Please Help me, anybody.
Upvotes: 1
Views: 460
Reputation: 105
You get the IP address of the connection by which the client is connecting to your server. If this is within the same network, you won't see a public IP address, because the connection is not routed over the internet.
Upvotes: 0
Reputation: 16049
There are couple of attributes of Request which provides client IP address. Here is the code:
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;
}
Hope it will work. ~Prasad
Upvotes: 1