Tuesday, January 19, 2010

Calculate the distance between 2 Ips in Java using maxmind

Calculating the distance between 2 ips can be done easily by using the great geo service: Maxmind.

Maxmind is an affordable geo service with broad range of solutions like:

  • Country
  • City
  • Organization
  • ISP

and more…

Maxmind services comes in 2 flavors:

  • Paid service: This is very accurate data, in a reasonable low cost.
  • Free service: This is a little less accurate data, but a totally free service.

In order to calculate the distance between 2 IPs, we will use the free version of Maxmind. The free service is called: geoLite. we will use the service named: geoLite city. The geoLite city data contains location information. The location contains latitude and longitude information for ip ranges. Latitude and longitude information is a coordinate method used in may location services such GPS.

In order to use Maxmind we need 2 things:

Calculating the distance between 2 IPs is very easy, since Maxmind did all the hard work for us. We just have to get “Location” instance for the 2 IP and use the “distance” method of the “Location” instance. The returned result is the distance between the 2 IPs in kilometers.

Let’s have a look at a sample code that calculates the distance between Google and Apple:

package com.bashan.blog.maxmind;
import com.maxmind.geoip.Location;
import com.maxmind.geoip.LookupService;
import java.io.IOException;
/**
 * @author Bashan
 */
public class MaxmindTest {
  public static void main(String args[]) throws Exception {
    LookupService lookupService = new LookupService("C:\\GeoLiteCity.dat");
    Location locationGoogle = lookupService.getLocation("74.125.39.147");
    Location locationMicrosoft = lookupService.getLocation("17.251.200.70");
    System.out.println("Google is located on: " + locationGoogle.city);
    System.out.println("Apple is located on: " + locationMicrosoft.city);
    System.out.print("Distance: " + locationGoogle.distance(locationMicrosoft) + " kilometers");
  }
}

And the output:

Google is located on: Mountain View
Apple is located on: Cupertino
Distance: 13.218970226605398 kilometers
Not too far as you can see… ;-)

No comments:

Post a Comment