You must Sign In to post a response.
  • Category: ASP.NET

    How to get client ip address while hitting our api ?

    How to get client ip address while hitting our api ?
  • #767308
    Hi,
    Try this:
    string szIpAddr= HttpContext.Current.Request.UserHostAddress;
    Or

    using System.Net.Http;
    using System.ServiceModel.Channels;
    using System.Web;
    using System.Web.Http;

    string szIpAddr="";
    HttpRequestMessage request = new Request;
    if (request.Properties.ContainsKey("MS_HttpContext"))
    {
    szIpAddr= (HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
    }
    else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
    {
    RemoteEndpointMessageProperty prop = (RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name];
    szIpAddr= prop.Address;
    }
    else if (HttpContext.Current != null)
    {
    szIpAddr= HttpContext.Current.Request.UserHostAddress;
    }

  • #767338
    Hi,

    If you want to get the client IP address first you need to get the server variables for "HTTP_X_FORWARDED_FOR" because client user is behind the proxy , his machine IP address the proxy server IP address append to the client IP address, after that the return result is null or empty then we will get the server variables for "REMOTE_ADDR" it returns the IP Address of the router and not the client user's machine.

    Ex:

    string ipadd;
    ipadd = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    if (ipadd == "" || ipadd == null)
    ipadd = Request.ServerVariables["REMOTE_ADDR"];


    Hope this will helpful to you...

    --------------------------------------------------------------------------------
    Give respect to your work, Instead of trying to impress your boss.

    N@veen
    Blog : http://naveens-dotnet.blogspot.in/

  • #767339
    what is ServerVariables ?

  • #767346
    Hi ajit,

    The servervarriables describes the name of the server which you want to retrieve details, if you want to know more details then go through the below link http://www.w3schools.com/asp/coll_servervariables.asp

    --------------------------------------------------------------------------------
    Give respect to your work, Instead of trying to impress your boss.

    N@veen
    Blog : http://naveens-dotnet.blogspot.in/

  • #767348
    with help of this example i am getting my server ip where api publish.

    Actually i want client IP address who is accessing my web api ?


Sign In to post your comments