繁体   English   中英

如何获取安卓模拟器的IP地址?

[英]How to get the Android Emulator's IP address?

我想通过代码获取当前运行的Android Emulator的 IP 地址。 如何实现?

澄清一下:在您的应用程序中,您可以简单地将模拟器称为“localhost”或 127.0.0.1。

Web 流量通过您的开发机器路由,因此模拟器的外部 IP 是您的提供商分配给该机器的任何 IP。 始终可以从您的设备在 10.0.2.2 访问开发机器。

由于您只询问仿真器的 IP ,您想要做什么?

如果您确实希望将 IP 分配给您的模拟器:

adb shell
ifconfig eth0

这会给你类似的东西:

eth0: ip 10.0.2.15 mask 255.255.255.0 flags [up broadcast running multicast]

像这样:

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

查看文档以获取更多信息: NetworkInterface

使用此方法,您将获得 100% 正确的 android 模拟器 IP 地址

获取你模拟器的ip地址

转到 adb shell 并键入此命令

adb shell
ifconfig eth0

在此处输入图片说明

运行此命令后,我得到

IP : 10.0.2.15

掩码:255.255.255.0

这对我有用。 我也在为一个网络应用程序工作。

如果您需要引用主机的 localhost,例如当您希望仿真器客户端联系运行在同一主机上的服务器时,请使用别名10.0.2.2来引用主机的环回接口。 从模拟器的角度来看, localhost(127.0.0.1)指的是它自己的环回接口。更多细节: http : //developer.android.com/guide/faq/commontasks.html#localhostalias

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

在我的应用程序代码中,我可以像下面一样轻松获取正在运行的设备 IP 地址:

WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM