我找到了解决方案。但这需要很长时间。给定代码尝试ping子网下的每个IP地址。例如,如果超时给出100ms,那么完成整个过程需要25.5秒。最佳方式是什么?
public class MainActivity extends Activity {
Button button;
EditText textview;
public String s_dns1 ;
public String s_dns2;
public String s_gateway;
public String s_ipAddress;
public String s_leaseDuration;
public String s_netmask;
public String s_serverAddress;
TextView info;
DhcpInfo d;
WifiManager wifii;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button1);
textview = (EditText)findViewById(R.id.ipList);
}
public void NetworkDetect(View v)
{
wifii = (WifiManager) getSystemService(Context.WIFI_SERVICE);
d = wifii.getDhcpInfo();
s_dns1 = "DNS 1: " + String.valueOf(d.dns1);
s_dns2 = "DNS 2: " + String.valueOf(d.dns2);
s_gateway = "Default Gateway: " + String.valueOf(d.gateway);
s_ipAddress = "IP Address: " + String.valueOf(d.ipAddress);
s_leaseDuration = "Lease Time: " + String.valueOf(d.leaseDuration);
s_netmask = "Subnet Mask: " + String.valueOf(d.netmask);
s_serverAddress = "Server IP: " + String.valueOf(d.serverAddress);
String connections = "";
InetAddress host;
StrictMode.ThreadPolicy policy = new StrictMode. ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try
{
host = InetAddress.getByName(intToIp(d.dns1));
byte[] ip = host.getAddress();
System.out.println("Start: ");
for(int i = 1; i <= 254; i++)
{
ip[3] = (byte) i;
InetAddress address = InetAddress.getByAddress(ip);
if(address.isReachable(100))
{
System.out.println(address + " machine is turned on and can be pinged");
connections+= address+"\n";
textview.append(address.toString()+"\n");
}
else if(!address.getHostAddress().equals(address.getHostName()))
{
System.out.println(address + " machine is known in a DNS lookup");
}
}
System.out.println("End");
}
catch(UnknownHostException e1)
{
e1.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
System.out.println(connections);
}
public String intToIp(int addr) {
return ((addr & 0xFF) + "." +
((addr >>>= 8) & 0xFF) + "." +
((addr >>>= 8) & 0xFF) + "." +
((addr >>>= 8) & 0xFF));
}
}