Topher
Topher

Reputation: 1029

Get client IP in Azure through MVC 5 controller

I can't find a question or post specific to Azure for this, and I'm not sure what's different in the environment in Azure versus my testing environments that would cause this. I've tried a few methods to get this to work but I'm not coming right. Please note this isn't Webapi, so using the HttpRequestMessage, as far as I know, is not going to work either.

Here's what I've tried so far:

Method 1:

string ipAddress = "";
IPHostEntry Host = default(IPHostEntry);
Host = Dns.GetHostEntry(System.Environment.MachineName);
ipAddress = Host.AddressList.SingleOrDefault(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).MapToIPv4().ToString();

Method 2:

string userIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(userIP))
{
    userIP = Request.ServerVariables["REMOTE_ADDR"];
}
return userIP;

Thanks in advance.

Upvotes: 3

Views: 1469

Answers (1)

evilSnobu
evilSnobu

Reputation: 26324

Read the value transported in this header:

x-forwarded-for: "91.23.44.24:52623"

Note there's a source port number trailing the IP address, so parse accordingly.

Also, as @NicoD correctly points out, the header in question may contain an array of proxy servers the request traversed. For example:

x-forwarded-for: "91.23.44.24:52623, 91.23.44.155"

Syntax

X-Forwarded-For: <client>, <proxy1>, <proxy2>

<client> The client IP address

<proxy1>, <proxy2> If a request goes through multiple proxies, the IP addresses of each successive proxy is listed. This means, the right-most IP address is the IP address of the most recent proxy and the left-most IP address is the IP address of the originating client.

What about that glaring port number you ask?

From https://www.rfc-editor.org/rfc/rfc7239:

5.2. Forwarded For

[...] this parameter MAY instead contain an IP address (and, potentially, a port number).

All client requests are terminated in the frontend layer and proxied via Application Request Routing to your web worker (hosting the MVC5 application).

App Service Application Request Routing

Upvotes: 3

Related Questions