0

I have MVC application on load balance server and I want to set real client's IP address. I added "X-Forwarded-For" on custom header and use c#.net code as below to get IP address but it return null. Please help me how I can check or how I can do. Thank you.

Add custom header :

Response.AddHeader("X-Forwarded-For", "client1, proxy1, proxy2");

c#.net code :

string IP_REMOTE_ADDR = string.Empty;
string IP_HTTP_X_FORWARDED_FOR = string.Empty;
string RETURN_IP = string.Empty;

IP_REMOTE_ADDR = string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]) ? "" : System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
IP_HTTP_X_FORWARDED_FOR = string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]) ? "" : System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

if (IP_HTTP_X_FORWARDED_FOR != "")
{
    RETURN_IP = IP_HTTP_X_FORWARDED_FOR;
    if (RETURN_IP.Contains(","))
    {
        RETURN_IP = RETURN_IP.Split(',')[0];
    }
}
else
{
    if(IP_REMOTE_ADDR != "")
    {
        RETURN_IP = IP_REMOTE_ADDR;
    }
    else
    {
        RETURN_IP = "";
    }
}

return RETURN_IP;
  • Maybe I'm confused, if you are sitting behind a load balanced how can you add the custom header to the client to get the root IP address. Adding this header should be controlled by the load balanced itself. And even if you get that up address how do you know it's not the address of a proxy at the client instead of the originating IP address? – Fran Oct 18 '17 at 11:41
  • I'm use load balance server provider, they told me other customer can get client IP address correctly and they advice me to use method as my question but it's not work. So I think maybe it's wrong from my application not server but I don't know what wrong. – ตอ เอ๋ย ตอเตย Oct 19 '17 at 04:54

0 Answers0