3

Q:-最近、プログラミングを使用して Android デバイスの IP アドレスを取得する際に問題に直面しています。その問題を解決するためのコードを誰かに教えてもらえますか。私はすでにそれについて多くのスレッドを読みましたが、そこから確かな答えを得ていません. それについて何か提案があれば教えてください。前もって感謝します。

4

2 に答える 2

4

問題は、現在使用中のネットワーク デバイスが実際にパブリック IP を持っているかどうかがわからないことです。ただし、これが事実であるかどうかを確認することはできますが、外部サーバーに接続する必要があります。

この場合、www.whatismyip.comを使用して確認できます (別の SO の質問からほぼコピーされています)。

public static InetAddress getExternalIp() throws IOException {
    URL url = new URL("http://automation.whatismyip.com/n09230945.asp");
    URLConnection connection = url.openConnection();
    connection.addRequestProperty("Protocol", "Http/1.1");
    connection.addRequestProperty("Connection", "keep-alive");
    connection.addRequestProperty("Keep-Alive", "1000");
    connection.addRequestProperty("User-Agent", "Web-Agent");

    Scanner s = new Scanner(connection.getInputStream());
    try {
        return InetAddress.getByName(s.nextLine());
    } finally {
        s.close();
    }
}

この IP がネットワーク インターフェイスの 1 つにバインドされていることを確認するには:

public static boolean isIpBoundToNetworkInterface(InetAddress ip) {

    try {
        Enumeration<NetworkInterface> nets = 
            NetworkInterface.getNetworkInterfaces();

        while (nets.hasMoreElements()) {
            NetworkInterface intf = nets.nextElement();
            Enumeration<InetAddress> ips = intf.getInetAddresses();
            while (ips.hasMoreElements())
                if (ip.equals(ips.nextElement()))
                    return true;
        }
    } catch (SocketException e) {
        // ignore
    }
    return false;
}

テストコード:

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

    InetAddress ip = getExternalIp();

    if (!isIpBoundToNetworkInterface(ip))
        throw new IOException("Could not find external ip");

    System.out.println(ip);
}
于 2012-06-14T10:47:38.843 に答える
2

Wi-Fi の場合:

WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();

または、より複雑なソリューション:

public String getLocalIpAddress() {
    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();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(LOG_TAG, ex.toString());
    }
    return null;
}
于 2012-06-14T10:10:38.690 に答える