如何使用IP获取国家代码和国家名称

hik*_*koo 3 java android

我是 Android 新手,我想使用 IP 地址获取国家/地区名称和国家/地区代码。请任何人指导我。

获取IP的代码如下:

public String getLocalIpAddress() {
    WifiManager wifiMgr = (WifiManager) getActivity().getSystemService(context.WIFI_SERVICE);
    if(wifiMgr.isWifiEnabled()) {
        WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
        int ip = wifiInfo.getIpAddress();
        String wifiIpAddress = String.format("%d.%d.%d.%d",
                (ip & 0xff),
                (ip >> 8 & 0xff),
                (ip >> 16 & 0xff),
                (ip >> 24 & 0xff));

        return wifiIpAddress;
    }else{
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    Log.i("","111 inetAddress.getHostAddress(): "+inetAddress.getHostAddress());
                    //the condition after && is missing in your snippet, checking instance of inetAddress
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        Log.i("","111 return inetAddress.getHostAddress(): "+inetAddress.getHostAddress());
                        return inetAddress.getHostAddress();
                    }

                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    return null;
}
Run Code Online (Sandbox Code Playgroud)

我不知道如何使用 IP 地址获取国家/地区代码和名称。

提前致谢!

Man*_*ger 5

1.) 查询您的公共IP地址:

public static String getPublicIP() throws IOException
    {
        Document doc = Jsoup.connect("http://www.checkip.org").get();
        return doc.getElementById("yourip").select("h1").first().select("span").text();
    }
Run Code Online (Sandbox Code Playgroud)

2.) 然后查询您的国家代码/姓名:(使用上述方法)

HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://ipinfo.io/"+getPublicIP());
HttpResponse response;
try {
    response = client.execute(request);

    Log.d("Response of GET request", response.toString());
} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
        e.printStackTrace();
} catch (IOException e) {
      // TODO Auto-generated catch block
     e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助。