4

I have a web API where I want to capture all incoming request public IP address inside my controller function.

manas sahu
  • 93
  • 2
  • 9
  • Do you want to get client's IP address from `HTTPRequestMessage` or from `Request`? – Prasad Telkikar Nov 16 '17 at 10:59
  • Could you define what you mean by public IP address? You have already been told how in the answer below. – Crowcoder Nov 16 '17 at 12:25
  • I want client internal IP not the hosted IP address , For reference please search whats my IP in google you will get your internal IP address.@Crowcoder – manas sahu Nov 16 '17 at 13:26
  • No, that is the public IP. You will never get the internal IP unless the client and server are on the same network. – Crowcoder Nov 16 '17 at 13:27
  • I want that public Ip which is showing in what my IP in Asp.net web form the below code is working fine but I want in web API controller @Crowcoder – manas sahu Nov 16 '17 at 13:50
  • So, based on the wealth of detail in your question I'm guessing you are testing where the client and server are on the same network. You won't get the public IP that way. You have to make the request go out to the interwebs. Trust us, when deployed to production this will return the IP you want. – Crowcoder Nov 16 '17 at 13:52
  • I hosted In UAT and check from mobile internet also it is taking my IPV4 IP address, not public IP Address Please check this api I want exact this ip address Url:- https://api.ipify.org?format=json @Crowcoder – manas sahu Nov 16 '17 at 15:22

1 Answers1

2

Check below code this must return you IP address of client

   protected string GetUser_IP()
    {
        string VisitorsIPAddr = string.Empty;
        if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
        {
            VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
        }
        else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
        {
            VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
        }
    return VisitorsIPAddr;
    }

For more help: Get public IP Address

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
  • 1
    I already tried with this. It's returning the hosted IP address not the public IP address – manas sahu Nov 16 '17 at 11:55
  • 1
    @manassahu, I answered 2 similar questions still requester is not satisfied my answer. Whenever you get working function for reading client IP , just post it. your answer will help me as well as to others. – Prasad Telkikar Nov 16 '17 at 13:11
  • please check this API. I want IP address the same which is being returned by this API https://api.ipify.org?format=json @Prasad telkikar – manas sahu Nov 16 '17 at 15:27