android – 使用ping列出本地网络上的设备

前端之家收集整理的这篇文章主要介绍了android – 使用ping列出本地网络上的设备前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试创建一个列出本地网络上所有连接设备的功能.
我所做的是ping地址空间x.x.x.0到x.x.x.255的任何地址,但它似乎无法正常工作.有人能以某种方式解释或扩展我的代码吗?我从电话(10.0.0.17)和默认网关(10.0.0.138)得到回复.后者甚至不应该在那里(事实上我不知道默认网关是什么,但忽略了).我虽然错过了这台电脑的IP.
  1. public ArrayList<InetAddress> getConnectedDevices(String YourPhoneIPAddress) {
  2. ArrayList<InetAddress> ret = new ArrayList<InetAddress>();
  3.  
  4. LoopCurrentIP = 0;
  5.  
  6. // String IPAddress = "";
  7. String[] myIPArray = YourPhoneIPAddress.split("\\.");
  8. InetAddress currentPingAddr;
  9.  
  10. for (int i = 0; i <= 255; i++) {
  11. try {
  12.  
  13. // build the next IP address
  14. currentPingAddr = InetAddress.getByName(myIPArray[0] + "." +
  15. myIPArray[1] + "." +
  16. myIPArray[2] + "." +
  17. Integer.toString(LoopCurrentIP));
  18.  
  19. // 50ms Timeout for the "ping"
  20. if (currentPingAddr.isReachable(50)) {
  21. if(currentPingAddr.getHostAddress() != YourPhoneIPAddress){
  22. ret.add(currentPingAddr);
  23.  
  24. }
  25. }
  26. } catch (UnknownHostException ex) {
  27. } catch (IOException ex) {
  28. }
  29.  
  30. LoopCurrentIP++;
  31. }
  32. return ret;
  33. }

解决方法

这是一个稍微修改过的循环,应该可以解决这个问题(至少对我有用);
  1. try {
  2. NetworkInterface iFace = NetworkInterface
  3. .getByInetAddress(InetAddress.getByName(YourIPAddress));
  4.  
  5. for (int i = 0; i <= 255; i++) {
  6.  
  7. // build the next IP address
  8. String addr = YourIPAddress;
  9. addr = addr.substring(0,addr.lastIndexOf('.') + 1) + i;
  10. InetAddress pingAddr = InetAddress.getByName(addr);
  11.  
  12. // 50ms Timeout for the "ping"
  13. if (pingAddr.isReachable(iFace,200,50)) {
  14. Log.d("PING",pingAddr.getHostAddress());
  15. }
  16. }
  17. } catch (UnknownHostException ex) {
  18. } catch (IOException ex) {
  19. }

猜你在找的Android相关文章