Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get client IP address in Azure Functions C#?

Tags:

I'm writing a function in C# using Azure Functions and need to get the ip address of the client that called the function, is this possible?

like image 882
TerryB Avatar asked Jun 02 '16 04:06

TerryB


People also ask

How can we get the IP address of the client?

Determining IP Address using $_SERVER Variable Method : There is another way to get the IP Address by using the $_SERVER['REMOTE_ADDR'] or $_SERVER['REMOTE_HOST'] variables. The variable in the $_SERVER array is created by the web server such as apache and those can be used in PHP.


2 Answers

Here is an answer based on the one here.

#r "System.Web"  using System.Net; using System.Web;  public static HttpResponseMessage Run(HttpRequestMessage req, TraceWriter log) {     string clientIP = ((HttpContextWrapper)req.Properties["MS_HttpContext"]).Request.UserHostAddress;     return req.CreateResponse(HttpStatusCode.OK, $"The client IP is {clientIP}"); } 
like image 57
David Ebbo Avatar answered Sep 20 '22 04:09

David Ebbo


you should use these function Get the IP address of the remote host

request.Properties["MS_HttpContext"] is not available if you debug precompiled functions local request.Properties[RemoteEndpointMessageProperty.Name] is not available on azure

private string GetClientIp(HttpRequestMessage request) {     if (request.Properties.ContainsKey("MS_HttpContext"))     {         return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress;     }      if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))     {         RemoteEndpointMessageProperty prop;         prop = (RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name];         return prop.Address;     }      return null; } 

Update 21.08.2018: Now Azure Functions are behind a LoadBalancer --> we have to inspect Request-Headers to determine the correct Client IP

private static string GetIpFromRequestHeaders(HttpRequestMessage request)     {         IEnumerable<string> values;         if (request.Headers.TryGetValues("X-Forwarded-For", out values))         {             return values.FirstOrDefault().Split(new char[] { ',' }).FirstOrDefault().Split(new char[] { ':' }).FirstOrDefault();         }          return "";     } 
like image 41
Brandy23 Avatar answered Sep 19 '22 04:09

Brandy23