So, I needed to find a way of fetching a website user's location using their IP address. A quick Google search found this stack overflow thread that mentioned a few options. I decided to try out the IPInfoDB API because it's free and seems to do exactly what I wanted.
The code (bear in mind I'm using C#) what pretty simple to write:
- Get the user's IP from the server variables (you'll want "REMOTE_ADDR")
- Fetch the response of the API (there's a good how-to at C# station for getting web requests with C#)
- Parse the XML (I used a linq XDocument, but you could parse it however you'd like)
I then stored the information in the session (so that I wouldn't need to make lots of requests to the service).
And there you go. Geo-location information from the IP address. The API goes down to city level, which is handy, although as expected the location isn't 100% accurate. My home IP returns my location as being several miles away, but at least it's in the right city :)
No comments:
Post a Comment