A simple service supply API return country from an IP address.
1. Setup necessary gems and create the database for project:
bundle install
bundle exec rake db:create db:migrate
2. Config your project directory before import:
- Edit
scripts/import
file - line 51 -rails_app_home
function
rails_app_home () {
cd /current/project/directory
}
- Edit
scripts/cron_import
file - line 4 -rails_app_home
function
rails_app_home () {
cd /current/project/directory
}
2. Import data:
./scripts/import
3. Run server and enjoy:
bundle exec rails s
4. Run the API:
URL: localhost:3000/ipaddresses
Type: GET
Parameter: ip_addr
5. Set the cronjob:
crontab scripts/cron_import
- The IP address available for free at http://download.ip2location.com/lite/. This service will auto-update the IP address every month.
- The cronjob will auto-run at 2:00 AM on the first of every month.
-
After download, the format of IP address is integer numbers.
-
The Import task will import the IP address from CSV files into the database.
-
The database will have two tables: Ipaddress and Country. The relation between two models: A country will have more IP addresses. An IP address will belong to one country.
-
Each line in CSV files is IP addresses in a range for a country. For example: 16778240 - 16779263 - AU - Australia. So, I think we need to convert the parameter
ip_addr
to integer and checkip_addr
is available or not in a range. -
How to convert the IP to integer? How to check the IP address is an IPv4 or IPv6? We can use this algorithm to converts and some Regexes for detect. But in the Ruby-core, we already have libraries for the tasks:
-
IPAddr IPAddr provides a set of methods to manipulate an IP address. Both IPv4 and IPv6 are supported.
-
Resolv IPv4 and Resolv IPv6 Resolv Ipv4 and Ipv6 will supply regex.
- I wrote 3 libraries:
- Countries - This library will return country codes and country name. The country code and names will be used in Country model. I downloaded the list of countries from this link: http://data.okfn.org/data/core/country-list
# models/country.rb
validates :code, inclusion: { in: Countries.new.country_codes }
validates :name, inclusion: { in: Countries.new.country_names }
-
IpConverter - This library will convert the ip address to integer.
-
IpUtilities - This library supply helpful methods.
- I've setup the Circle CI and Ruby-Saddler to run test cases and check the coding style.
Actually, this service is built in short time, so some parts need to be improved.
-
Performance for import task progress.
-
The import script needs to refactor.
-
Need to refactor the code and write more the test cases.