I agree with above answers, the best way to get country from ip address is Maxmind.
If you want to write code in java, you might want to use i.e. geoip-api-1.2.10.jar and geoIP dat files (GeoIPCity.dat), which can be found via google.
Following code may be useful for you to get almost all information related to location, I am also using the same code.
public static String getGeoDetailsUsingMaxmind(String ipAddress, String desiredValue)
{
Location getLocation;
String returnString = "";
try
{
String geoIPCity_datFile = System.getenv("AUTOMATION_HOME").concat("/tpt/GeoIP/GeoIPCity.dat");
LookupService isp = new LookupService(geoIPCity_datFile);
getLocation = isp.getLocation(ipAddress);
isp.close();
//Getting all location details
if(desiredValue.equalsIgnoreCase("latitude") || desiredValue.equalsIgnoreCase("lat"))
{
returnString = String.valueOf(getLocation.latitude);
}
else if(desiredValue.equalsIgnoreCase("longitude") || desiredValue.equalsIgnoreCase("lon"))
{
returnString = String.valueOf(getLocation.longitude);
}
else if(desiredValue.equalsIgnoreCase("countrycode") || desiredValue.equalsIgnoreCase("country"))
{
returnString = getLocation.countryCode;
}
else if(desiredValue.equalsIgnoreCase("countryname"))
{
returnString = getLocation.countryName;
}
else if(desiredValue.equalsIgnoreCase("region"))
{
returnString = getLocation.region;
}
else if(desiredValue.equalsIgnoreCase("metro"))
{
returnString = String.valueOf(getLocation.metro_code);
}
else if(desiredValue.equalsIgnoreCase("city"))
{
returnString = getLocation.city;
}
else if(desiredValue.equalsIgnoreCase("zip") || desiredValue.equalsIgnoreCase("postalcode"))
{
returnString = getLocation.postalCode;
}
else
{
returnString = "";
System.out.println("There is no value found for parameter: "+desiredValue);
}
System.out.println("Value of: "+desiredValue + " is: "+returnString + " for ip address: "+ipAddress);
}
catch (Exception e)
{
System.out.println("Exception occured while getting details from max mind. " + e);
}
finally
{
return returnString;
}
}