Falls noch jemand daran Interesse hatt, mal meine quick and dirty zusammengehackte Lösung:
Die zugrunde liegende Datei ip2country.db gibt es auf:
ip-countryside - Creates an accurate ip-to-country database out of the RIR information. - Google Project Hosting
Klasse Main:
[Java]
package pack;
import java.net.*;
public class Main
{
private static IPUtil util = new IPUtil();
public static void main(String[] args)
{
try
{
URL url = new URL("http://ehm.homelinux.org/MyOggRadio");
long ip = util.getIPFromURL(url);
String country = util.getCountryFromIP(ip);
System.out.println(">>" + country);
}
catch (Exception e)
{
System.out.println("Main:main:Exception:");
System.out.println(e.toString());
}
}
}
[/Java]
Klasse IPUtil:
[Java]
package pack;
import java.io.*;
import java.net.*;
public class IPUtil
{
private File db = new File("/home/christian/ip2country.db");
public String getCountryFromIP(long ip)
{
String erg = "unbekannt";
try
{
Reader reader = new FileReader(db);
BufferedReader br = new BufferedReader(reader);
String satz = br.readLine();
while (satz != null)
{
String country = test(satz,ip);
if (country != null)
{
erg = country;
break;
}
satz = br.readLine();
}
br.close();
}
catch (Exception e)
{
System.out.println("IPUtil:getCountryFromIP:Exception:");
System.out.println(e.toString());
System.out.println(ip);
}
return erg;
}
private String test(String satz,long ip)
{
satz += " ";
String erg = null;
String ip1 = "";
String ip2 = "";
String c = "";
String x = "";
int n = 0;
for (int i=0;i<satz.length();i++)
{
String ch = satz.substring(i,i+1);
if (ch.equals(" "))
{
n++;
if (n == 1) ip1 = x;
if (n == 2) ip2 = x;
if (n == 3) c = x;
x = "";
}
else
{
x += ch;
}
}
try
{
long lip1 = new Long(ip1).longValue();
long lip2 = new Long(ip2).longValue();
if (lip1 <= ip & ip <= lip2) erg = c;
}
catch (Exception e)
{
System.out.println("IPUtil:test:Exception:");
System.out.println(e.toString());
System.out.println(satz);
}
return erg;
}
public long getIPFromURL(URL url)
{
long erg = 0;
try
{
InetAddress adr = InetAddress.getByName(url.getHost());
String ip = adr.getHostAddress() + ".";
long l1 = 0;
long l2 = 0;
long l3 = 0;
long l4 = 0;
String x = "";
int n = 0;
for (int i=0;i<ip.length();i++)
{
String ch = ip.substring(i,i+1);
if (ch.equals("."))
{
n++;
if (n == 1) l1 = new Long(x).longValue();
if (n == 2) l2 = new Long(x).longValue();
if (n == 3) l3 = new Long(x).longValue();
if (n == 4) l4 = new Long(x).longValue();
x = "";
}
else
{
x += ch;
}
}
erg = l4 + l3 * 256 + l2 * 256 * 256 + l1 * 256 * 256 * 256;
}
catch (Exception e)
{
erg = 0;
System.out.println("IPUtil:getIPFromURL:Exception:");
System.out.println(e.toString());
System.out.println(url.toString());
}
return erg;
}
}
[/Java]