2011-01-20 168 views

回答

0
+0

其实我已经试过这个代码了。但我认为WifiManager不适用于Android模拟器。它给了我错误。它会给出一个主机的IP地址。我想要网络中的所有计算机 – Bhagya 2011-01-20 17:45:27

+0

此处的代码在Emulator上也适用于我 - > http://www.droidnova.com/get-the-ip-address- 304.html – HT03 2011-01-20 19:34:02

2

可以共享logcat的,我怀疑可能有一些其他issue.Try该代码(这是)在一个示例应用程序只检查的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)) 
1

正如另一个主题所述,android模拟器工作在虚拟专用网络上。

这意味着模拟器与您的计算机不在同一个网络上,而是在虚拟网络上。没有仿真器可以看到其他设备,也没有其他仿真器,也没有其他设备可以看到仿真器。

除此之外,我有一个问题:

我怎样才能使用WifiManager一个主机的IP地址?

例如,我的电脑与我的android手机(不是仿真器)在同一个局域网上,并且它有一个像User-PC这样的主机名。当我尝试使用InetAddress.getByName(“User-PC”)获取IP时;在一个Java应用程序中,我得到了像192.168.1.100那样的局域网IP,但是当我在电话上尝试时,它不起作用。奇怪的是,如果我知道IP,我可以建立连接,但似乎无法解决它主机名。

任何想法?

1

如果你想检测连接到任何网络的“模拟器”或Android设备的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()); 
     }