簡體   English   中英

如何在Android中獲取主機IP地址?

[英]How to get Host IP address in android?

問:現在我在使用編程獲取Android設備的IP地址時遇到問題。 任何人都可以給出解決該問題的代碼。 我已經閱讀了很多關於它的帖子,但沒有從中獲得可靠的答案。 請給我任何建議,贊賞它。 提前致謝。

問題是你無法知道你當前使用的網絡設備是否真的有公共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是否綁定到您的某個網絡接口:

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);
}

對於wifi:

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM