Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

clojure

ring

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

like image 988
leontalbot Avatar asked May 03 '15 18:05

leontalbot


2 Answers

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)))
like image 181
leontalbot Avatar answered Sep 22 '22 07:09

leontalbot


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))
like image 40
Bill Avatar answered Sep 22 '22 07:09

Bill