Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 832
Dan Avatar asked Oct 30 '25 13:10

Dan


1 Answers

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();
            }
like image 97
Nisarg Parikh Avatar answered Nov 01 '25 06:11

Nisarg Parikh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!