IPアドレスから国を取得する (Java)

package hello.java.net;

import java.net.InetAddress;

import java.net.UnknownHostException;

public class InetAddressLookUpMain {

// see http://cc.wariate.jp/

static String baseHost = "cc.wariate.jp";

static String[] locales = "JP,US,KR,CH,HK".split(",");

public static String getCountry(String s) throws UnknownHostException {

InetAddress inetAddr = InetAddress.getByName(s); // throws

// UnknownHostException

byte[] byteAddr = inetAddr.getAddress();

StringBuffer sb = new StringBuffer();

for (int i = (byteAddr.length - 1); i >= 0; i--) {

int unsignedByte = byteAddr[i] < 0 ? byteAddr[i] + 256

: byteAddr[i];

sb.append(unsignedByte + ".");

}

for (int n = 0; n < locales.length; n++) {

String country = locales[n];

String lookupHost = sb.toString() + country.toLowerCase() + "."

+ baseHost;

try {

InetAddress.getByName(lookupHost);

return (locales[n]);

} catch (UnknownHostException e) {

// e.printStackTrace();

}

}

return null;

}

public static void main(String[] args) throws Exception {

System.out.println(getCountry("www.yahoo.co.jp"));

System.out.println(getCountry("www.ibm.com"));

System.out.println(getCountry("daum.net"));

System.out.println(getCountry("weibo.com"));

System.out.println(getCountry("aho"));

}

}

---

JP

US

KR

HK

Exception in thread "main" java.net.UnknownHostException: aho: aho

at java.net.InetAddress.getAllByName0(InetAddress.java:1270)

at java.net.InetAddress.getAllByName(InetAddress.java:1197)

at java.net.InetAddress.getAllByName(InetAddress.java:1119)

at java.net.InetAddress.getByName(InetAddress.java:1069)

at hello.java.net.InetAddressLookUpMain.getLocale(InetAddressLookUpMain.java:14)

at hello.java.net.InetAddressLookUpMain.main(InetAddressLookUpMain.java:55)

---

IPアドレスから国を取得する Java

IP Address Country Java