Search code examples
httpscalaip-addressakkaspray

How to get incoming IP address in Spray framework


I am looking at headers that are coming in, but no IP seems to be there:

HttpRequest(GET,http://127.0.0.1:8080/track/check,List(Accept-Language: uk-UA, 
uk, ru, en-US, en, Encoding: gzip, deflate, sdch, User-Agent: Mozilla/5.0 
(Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29
Safari/537.36, Accept: text/html, application/xhtml+xml, application/xml;q=0.9, 
*/*;q=0.8, Connection: keep-alive, Host: 127.0.0.1:8080),EmptyEntity,HTTP/1.1)

This is a request I did from browser. Basically I am looking in:

path("check") {
       get {
         implicit request => {
           val a = 5
         }
       }
     } ~

Here request object doesn't have any information about the IP address. Any help is very appreciated. thanks.


Solution

  • If you are using spray routing, then there is a directive for extracting client ip called clientIP =) To use it just write:

    (path("somepath") & get) {
      clientIP { ip =>
        complete(s"ip is $ip")
      }
    }
    

    more then simple, but you need still need to add explicit configuration to get IP from request. And a little comment, maybe i didn't get something but in spray there is no implicit request. Actually incoming request percolates through your routing structure, if you take a look into the routing library you'll see that route is just an alias: type Route = RequestContext => Unit. So if you need to get access to the context at some point just write:

    (path("somepath") & get) {
      clientIP { ip => 
        reqCont => reqCont.complete(s"ip is $ip")
      }
    }
    

    But remember about static route part and dynamic part.