繁体   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