直接上代码:
WifiManager wifi_service = (WifiManager)getSystemService(WIFI_SERVICE);
DhcpInfo dhcpInfo = wifi_service.getDhcpInfo();
new Thread(new Runnable() {
@Override
public void run() {
List<String> list = new ArrayList<>();
InetAddress host;
try
{
host = InetAddress.getByName(intToIp(dhcpInfo.dns1));
byte[] ip = host.getAddress();
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");
String ipAddress = address.toString().replace("/","");
list.add(ipAddress);
}
else if(!address.getHostAddress().equals(address.getHostName()))
{
System.out.println(address + " machine is kNown in a DNS lookup");
}
}
}
catch(UnknownHostException e1)
{
e1.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}).start();
还有一种方法:
private List<String> getConnectIp() throws Exception {
List<String> connectIpList = new ArrayList();
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("ip neigh show");
proc.waitFor();
BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
String[] splitted = line.split(" +");
if (splitted != null && splitted.length >= 4) {
String ip = splitted[0];
connectIpList.add(ip);
}
}
return connectIpList;
}