matix.io

How to get a user's city or country from their IP address

July 28, 2021

How can I retrieve a user's city or country from their IP address?

In this article, we'll cover the basics of IP geolocation, to answer the following questions:

  1. How does IP geolocation work?
  2. How can I convert an IP address into a city or a country?

How does IP geolocation work?

In order to understand how IP geolocation works, we have to understand how IP addresses are allocated.

How are IP addresses allocated?

At the top level, all numbers are allocated by the Internet Assigned Numbers Authority (IANA). But how does a normal user receive their IP address?

Let's start by looking at how you get your internet connection. It's very likely that you connect to the internet via a wired connection, a mobile connection, or a satellite connection. However you connect, you have a contract with your Internet Service Provider (ISP) to provide you with access to the internet. Whenever you connect to the internet, your ISP provides you with an IP address.

How does your ISP choose which IP address to give you? They have a block of IP addresses that they have been allocated by a higher authority. Ultimately, there is a chain of authorities which leads back to IANA. Each authority in the chain handles a geographic region. At the top we have the global authority, IANA. In the middle, we have continental authorities, national authorities, regional authorities & city-level authorities. Finally, we have ISPs, who ultimately grant the addresses to the customers.

Why is this important? Because IP addresses are allocated by geographic region, which allows us to perform our IP geolocation task.

How can I know which geographic region an IP address belongs to?

Unfortunately, an IP address does not have the geographic information encoded in it. We need to make use of a third-party database that keeps track of allocated blocks of IP addresses. Luckily, such a database is publicly available: the MaxMind GeoIP2 database.