get Ip address of computers in WIFI network on And

2019-06-01 04:31发布

I would like to programmatically find the IP addresses of computers which are connected via WiFi to an Android device or emulator. How do I do this?

4条回答
smile是对你的礼貌
2楼-- · 2019-06-01 04:49

If you want to detect the ip address of the "Emulator" or android device which is connected to any Network then use this code in Your program. it will give you the exact IP Address which the network have assign to your device.

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());
      }
查看更多
太酷不给撩
3楼-- · 2019-06-01 04:52

As stated in another topic, the android Emulator works on a virtual private network.

Which means that the emulator is NOT on the same network as your computer, but on a virtual one. No emulator can see other devices, nor other emulators, nor other devices can see the emulators.

Apart from that I have a question:

How can I get the IP address of a hostname using the WifiManager?

For example, my PC is on the same LAN as my android phone (not emulator), and it has a hostname like User-PC. When I try to get the IP with InetAddress.getByName("User-PC"); on a java application, I get the LAN IP like 192.168.1.100, but when I try it on the phone it doesn't work.. Weird thing is I can establish connections if I know the IP, but cant seem to resolve it from the hostname.

Any ideas?

查看更多
一纸荒年 Trace。
4楼-- · 2019-06-01 04:56

Can you share the logcat, I suspect there might be some other issue.Try this code (as is) in a sample application to check only if Wi-Fi IP address is working

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))
查看更多
登录 后发表回答