How to Identify Country by IP Address

Kamol
By DevOps For DevOps
2 min readAug 1, 2022

At some point in your engineering life, you will face the question: “Is there a way to figure out the country name just by looking at an IP address?”.

Yes, there are many ways, and we will share them with you in this article (of course, with source code and solutions).

Option 1: How to Identify Country by IP Address in Golang Code

We have written a small microservice(source code) in Golang using a geolocation database from MaxMind.

If you would like to run and test on your system quickly, follow the following steps:

  1. Clone the microservice-geoip repo:
git clone git@github.com:By-DevOps-For-DevOps/microservice-geoip.git
cd microservice-geoip

2. Run go get in the microservice-geoip to download golang required source code and dependencies.

go get

3. Run the following command lines

export PORT=9090
go run main.go

4. Now you can access your browser with the following URL(http://localhost:9090/country?ip=147.191.99.35) or from a command line

➜  http http://localhost:9090/country\?ip\=147.191.99.35
HTTP/1.1 200 OK
Content-Length: 2
Content-Type: text/plain; charset=utf-8
Date: Mon, 01 Aug 2022 02:41:15 GMT
US

As you can see from your browser or from your command line the IP address (147.191.99.35) is allocated in the USA.

What about IPv6?

MaxMind stores IPv4 addresses in an IPv6 tree, occupying the first 32 bits of the address space (0 to 2²³-1). Which allows us to use the same DB and code to look up IPv4 and IPv6. E.g. with IPv6:

http://localhost:9090/country?ip=240d:1a:4b1:2400:5d54:dcbe:95b7:def5

Conclusion

That’s it! Try our Golang code to identify countries by IP address. Ask any questions or provide any feedback. We will be happy to help you.

Meanwhile, we will add more options with AWS Lambda, CloudFlare, etc. Please stay tuned. Follow us for further updates.

Disclaimer: The authors are not affiliated with MaxMind.

--

--