Getting all the ASNs of a country using our free IP to Country ASN database

Downloading the CSV version of the IP to Country ASN database

You can choose from many ways to download the IP to Country ASN database in CSV format. For example:

We will use the CLI-based download, as this step already takes care of uncompressing the database natively and you don’t have to run a separate command.

ipinfo download country-asn -f csv

You might see a checksum-related error, but that is a bug as we are computing checksums on the unzipped version. We will fix that.

0507-ezgif.com-video-to-gif-converter

Getting the ASNs from a particular country

Let’s take a close look at our IP to Country ASN database.

Let’s make our lookup country “Saudi Arabia.” For that, we are going to grep the country name from the country_asn.csv file by wrapping it in commas like so ,Saudi Arabia,.

Let’s store the grepped IP ranges column in a file called, saudi_arabia_ranges.csv

grep ",Saudi Arabia," country_asn.csv > saudi_arabia_ranges.csv

Using country code to grep the IP to Country ASN database will result in errors because this database contains continent codes that conflict with country codes. For example, NA can refer to the country Namibia as well as the continent North America.

From there, we just want the ASN values. The ASN values are stored in the 7th column. By using awk and sed, you can extract the ASN values. Then, you have to obtain the unique values by using sort -u. Finally, we are going to store it in a file called asns.txt.

awk -F "\"*,\"*" '{print $7}' saudi_arabia_ranges.csv | sed 's/^"\(.*\)"$/\1/' | sort -u > asns.txt
  • awk -F "\"*,\"*": This sets the field separator as any number of commas enclosed by double quotes. This helps to handle the escaped commas correctly.
  • saudi_arabia_ranges.csv: Our grepped ranges that contain IP range information of Saudi Arabia.
  • {print $7}: This prints the 7th column.
  • sed 's/^"\(.*\)"$/\1/': This removes the surrounding double quotes from each value. It captures the content between the quotes and prints it without the quotes.
  • sort -u: Gets only the unique ASN values.

The command might look complicated, but it isn’t. All of the double quotes (") you are seeing are to ensure that we properly escape natural commas inside double quotes.

WindowsTerminal_EuhFMFDCJm

And that’s it after running the command you will be presented with an ASN list in the asns.txt file which will contain all the ASNs for the country of Saudi Arabia.

AS10122
AS109
AS11351
AS1136
AS11403
AS11488
AS116
AS1221
AS1239
AS12529
[....]

Let me know if you have any feedback. Thanks!