Search code examples
clojurering

How to get the client IP address in ring-clojure?


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"}


Solution

  • 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)))