Dan
Dan

Reputation: 5972

RemoteIpAddress in K8S Cluster is always the ingress IP

I have an ASP.NET Core webapi running in an on-prem bare-metal Kubernetes cluster. There's no external load-balancer, and I'm using NGINX ingress.

I want to get the users' IP address, and am using HttpContext.Connection.RemoteIpAddress in the .NET code.

Unfortunately, this is picking up the IP address of the nginx ingress (possibly the controller given the namespace)...

::ffff:10.244.1.85

Doing a reverse DNS lookup resolves that to...

10-244-1-85.ingress-nginx.ingress-nginx.svc.cluster.local

After a little bit of Googling, I tried adding externalTrafficPolicy: "Local" to my service definition, but that didn't make a difference.

This seems like something that should be really trivial and quite a common requirement. Any ideas?

Upvotes: 4

Views: 1000

Answers (1)

Nisarg Parikh
Nisarg Parikh

Reputation: 51

First try to get ip from header X-Forwarded-For as shown below, if it's null then you can use Connection.RemoteIpAddress. Also make sure your nginx configmap has proxy enabled as per screenshot:
enter image description here

var ip = IPAddress.Parse(_accessor.ActionContext.HttpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault());
            if (string.IsNullOrEmpty(ip.ToString()))
            {
                ip = _accessor.ActionContext.HttpContext.Connection.RemoteIpAddress.MapToIPv4();
            }

Upvotes: 4

Related Questions