dhruvrajvanshi / Moonshine

Web framework for Crystal language [DEPRECATED in favour of kemal]
MIT License
121 stars 11 forks source link

client IP #4

Closed 5nyper closed 9 years ago

5nyper commented 9 years ago

How do I go about getting the visitors IP?

mrtryhard commented 9 years ago

Something along the lines of : headers["REMOTE_ADDR"]

Note that if this returns nil, you should probably try something like
headers["HTTP_X_FORWARDED_FOR"]

This is a raw way of doing things and I didn't test it either. Also, do not forget that IP addresses can easily be spoofed and are not reliable :-(

Maybe the author can offer a better detailed example. I haven't used the framework yet :^)

dhruvrajvanshi commented 9 years ago

There's currently no better way than what mrtryhard suggested. EDIT: headers is a property of a Moonshine::Request object eg.

    app.route "/", do |req|
        ip = req.headers["REMOTE_ADDR"]
        ok("#{ip}")
    end

Note that this will raise an exception if the client doesn't send the REMOTE_ADDR header

mrtryhard commented 9 years ago

Thanks for the example! Does it raise an exception because the key isn't found in headers?

5nyper commented 9 years ago

Yeah both REMOTE_ADDR and HTTP_FORWARDED dont work :(

dhruvrajvanshi commented 9 years ago

You can try printing out the request headers to see if any ip is found there. Otherwise, you're out of luck. It is up to the client (browser) and the proxy servers between client and server to set(or unset) the REMOTE_ADDR header. Which browser are you using? A better way to identify clients is to use session cookies. Hopefully, I will be able to add session handling soon.