There used to be a free database that provided a list of IP address ranges by country. It was available at http://software77.net/geo-ip>software77.net/geo-ip. (You could probably create it yourself by merging files from regional registries, e.g. ftp://ftp.arin.net/pub/stats/NIC/delegated-NIC-latest, where NIC is one of afrinic, apnic, arin, lacnic, ripencc)

I have written a Python script that converts it into a yaml email filter, which is the only format my web host supports. The script is available here. Just place it in the same folder as IpToCountry.csv file and run it from the command line as:
$ cd IpToCountry (or wherever you have placed the files)
$ iptoc2filter.py
It will create a file "filter.yaml" that you can upload to the web server. On my site it goes into ~/.cpanel. After upload, you have to activate it by logging to cpanel, going to "Account Level Filtering", clicking "Edit" (any, but I usually click on the one on the last line, to preserve order), then clicking "Activate".
If there are files in the same folder, named "filter-prolog.yaml" and/or "filter-epilog.yaml", they will be included in the front/back of the resulting filter. I use prolog for a whitelist of email addreses in countries that would otherwise be marked as spam, SpamAssasin, and other filters that should be processed first. I use epilog for a list of spam sources in countries like US and Canada, which are excluded in main filter.
At the top of the script, there are two parameters that you should change (where to put spam) and several parameters, that you can change, like the list of countries to exclude, countries that are gray (maybe-spam) and destination folders for probable-spam and for sure-spam. Mail from countries which are not excluded and not in probably-spam, will go to sure-spam.
You may want to create a separate email accounts for probable-spam and for sure-spam. That is what I did.

The script can also take an argument to produce:

It can also run several tests, including testing regular expressions created for the filter.yaml. See the code for details.

If you find a bug or have an idea for improvement, please, let me know. Thanks.


To lookup single IP address or all address ranges for a country, click here.