Is it possible to get the IP address of an incoming request in a Kemal webapp?

Hi,

Is it possible to get the IP address of an incoming request in a Kemal webapp? I saw this old issue on Kemal repo (how can i get client ip? · Issue #319 · kemalcr/kemal · GitHub), but there was no solution (other than when the app is behind nginx).

I printed out the header of a request (to an app on localhost), but there was no IP field in the headers either. I would appreciate if someone could point out whether it is possible to get the client’s IP address, and if yes, how? It appears to me that unwanted parties are trying to access the application, and I want to ban the problem IPs.

Thank you.

Disclaimer: This is not as trivial as it sounds for general applications when you don’t know how it is deployed. For example, the connecting IP address could be an actual client or a reverse proxy. On the other hand, a client IP header could be legitimately forwarded by a reverse proxy or forged by a malicious client.

If you’re operating the service yourself and don’t use any reverse proxy, you can reasonably assume the remote IP to be the client. (Except that there are many ways this could be something else, like a normal proxy)

You should be able to get the remote address from HTTP::Request#remote_address. In a Kemal handler (or any Crystal HTTP::Server handler), the request is available as context.request.

2 Likes

Thank you for your response @straight-shoota. Very sorry for the delay in responding. I will try out the context.request, but I value your related comments about the pitfalls in using this approach. I will probably add a custom challenge for login, that will make invalid attempts difficult.

Thank you again.