当访问者提交表单时,我想联系他们输入他的IP地址.
(POST "/form" {params :params} (assoc params :ip-address the-ip)
Run Code Online (Sandbox Code Playgroud)
这该怎么做?
想到这样做:
(POST "/form" {params :params
client-ip :remote-addr}
(->> params keywordize-keys (merge {:ip-address client-ip}) str))
Run Code Online (Sandbox Code Playgroud)
但这会回来 {... :ip-address "0:0:0:0:0:0:0:1"}
从Arthur Ulfeldt的评论到Bill的回答,我想我们可以这样写:
(defn get-client-ip [req]
(if-let [ips (get-in req [:headers "x-forwarded-for"])]
(-> ips (clojure.string/split #",") first)
(:remote-addr req)))
Run Code Online (Sandbox Code Playgroud)
:remote-addr除非您坐在负载均衡器后面,否则从请求对象中获取通常是正确的方法。在这种情况下,您的负载平衡可能会x-forwarded-for在请求中添加一个标头。这将使这样的事情变得合适。
(or (get-in request [:headers "x-forwarded-for"]) (:remote-addr request))
Run Code Online (Sandbox Code Playgroud)