Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the user's country for a HTTP request in the Backend?

I am trying to get the country where the user is sending the request to my server.

So far I have found those solutions:

https://github.com/fiorix/freegeoip

https://github.com/maxmind/GeoIP2-java

These solutions are using MaxMind database GeoIP2 Country Database which has a license and for this specific project I have restriction with Libraries (legal aspects because of the business)

I have found some topics mentioning that Google API can provide this service, but that doesn't interest me as I want a solution that I can host myself and it is implemented using Java or Kotlin.

Does someone know a solution different from the one mentioned (that runs on the backend)?

like image 986
Roberto Ferraz Avatar asked Sep 28 '17 08:09

Roberto Ferraz


People also ask

How can I tell where a HTTP request came from?

There is absolutely no way to know with certainty if a request came from a browser or something else making an HTTP request. The HTTP protocol allows for the client to set the User Agent arbitrarily.

How do I get the country header?

To retrieve the country code, just check the header named HTTP_CF_IPCOUNTRY and you'll have the value. You can then easily perform some logic based on country of origin. Much easier.

What are the HTTP request methods?

The most commonly used HTTP request methods are GET, POST, PUT, PATCH, and DELETE. These are equivalent to the CRUD operations (create, read, update, and delete).

Can we retrieve data using POST method?

Yes, you can make it work at least using WCF, it's bit different in MVC and Web API where you add attributes to methods like [GET] [POST] etc..


1 Answers

I've coded a little service that returns the country based on data I've acquired from http://ipverse.net/

It should be license free but correct me if I am wrong. According to the website the data is provided by the five big RIRs.

The website updates its data ~5am. The Cron job that updates the IP Blocks is scheduled at 6am. The data should be accurate I guess.

*edit I've replicated the algo and created a github action to keep it updated, check it out: https://github.com/jaecktec/ncc-inetnum-parser

like image 197
Coco Avatar answered Oct 18 '22 18:10

Coco