Reputation: 2543
When a visitor submit a form, I'd like to assoc to inputs his IP adress.
(POST "/form" {params :params} (assoc params :ip-address the-ip)
How to do this?
Thought of doing this:
(POST "/form" {params :params
client-ip :remote-addr}
(->> params keywordize-keys (merge {:ip-address client-ip}) str))
But this returns {... :ip-address "0:0:0:0:0:0:0:1"}
Upvotes: 8
Views: 2763
Reputation: 2543
From Arthur Ulfeldt's comment to Bill's answer, I guess we could write this:
(defn get-client-ip [req]
(if-let [ips (get-in req [:headers "x-forwarded-for"])]
(-> ips (clojure.string/split #",") first)
(:remote-addr req)))
Upvotes: 9
Reputation: 12883
Getting :remote-addr
from the request object is typically the correct way to go unless you're sitting behind a load balancer. In that case your load balance may add a header e.g. x-forwarded-for
to the request. Which would make something like this appropriate.
(or (get-in request [:headers "x-forwarded-for"]) (:remote-addr request))
Upvotes: 6
Reputation: 4235
I'm pretty sure you can get this information from the ring request object. Have a look at the ring.middleware.dump (handle-dump) package. If you set that up and a simple route to use it, you will get a nice web page showing all the available values provided in a ring request object. Pretty sure this includes the client IP address. As this information is obtained from the http headers, it will likely be more reliable than manually putting it into your request parameters - putting it into your request parameters either using a form or json could mean it is easier to forge. Besides, if it is already readily available as part of the request object, means one less ting you need to do.
Upvotes: 1