【发布时间】:2011-06-12 14:14:16
【问题描述】:
我想以编程方式查找通过 WiFi 连接到 Android 设备或模拟器的计算机的 IP 地址。我该怎么做?
【问题讨论】:
我想以编程方式查找通过 WiFi 连接到 Android 设备或模拟器的计算机的 IP 地址。我该怎么做?
【问题讨论】:
你能分享一下 logcat,我怀疑可能还有其他问题。在示例应用程序中尝试此代码(原样),以检查 Wi-Fi IP 地址是否正常工作
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
String ip = null;
ip = String.format("%d.%d.%d.%d",
(ipAddress & 0xff),
(ipAddress >> 8 & 0xff),
(ipAddress >> 16 & 0xff),
(ipAddress >> 24 & 0xff))
【讨论】:
如另一个主题所述,android Emulator 可在虚拟专用网络上运行。
这意味着模拟器与您的计算机不在同一网络上,而是在虚拟网络上。没有模拟器可以看到其他设备,也没有其他模拟器,也没有其他设备可以看到模拟器。
除此之外我还有一个问题:
如何使用 WifiManager 获取主机名的 IP 地址?
例如,我的 PC 与我的 android 手机(不是模拟器)在同一个 LAN 上,并且它的主机名类似于 User-PC。当我尝试使用 InetAddress.getByName("User-PC"); 获取 IP 时在Java应用程序上,我得到了像192.168.1.100这样的LAN IP,但是当我在电话上尝试它时它不起作用。奇怪的是,如果我知道IP,我可以建立连接,但似乎无法解决它主机名。
有什么想法吗?
【讨论】:
如果您想检测连接到任何网络的“模拟器”或安卓设备的 IP 地址,请在您的程序中使用此代码。它会为您提供网络分配给您设备的确切 IP 地址。
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())
{
String Ip= inetAddress.getHostAddress().toString();
//Now use this Ip Address...
}
}
}
}
catch (SocketException obj)
{
Log.e("Error occurred during IP fetching: ", obj.toString());
}
【讨论】: