Brad Lucas

A blog mostly about programming
June 24, 2017

Showip Example In Clojure

I found a small example I wrote last year. It shows the ip address of the machine from which the program is running. It does so by calling http://httpbin.org/ip. This url returns the callers IP address in JSON.

The example shows get-ing a url and parsing the JSON.

To access the url I'm using clj-http. This returns a map from which you want the value of :body.

The JSON return value will look like this:

{
    "origin": "8.8.8.8, 72.80.131.168"
}

To parse this I'm using clojure.data.json and it's read-str function which converts the result into a map. Once in a mapp you grab the "origin" value.

Lastly, you want the IP so I split the string on the comma and return the second value.

Code

The main function contains the following:

  (let [url "http://httpbin.org/ip"
        result (json/read-str (:body (client/get url {:headers {:X-Forwarded-For "8.8.8.8"}})))]
    (clojure.string/trim (second (clojure.string/split (get result "origin") #",")))
    ))


Tags: clojure