1)核心代码
如果我们想要确定自己所在的局域网的所有用户,我们可以通过这种方式获取:
步骤如下:
首先获取本机地址,截取自己所在的网段
然后调用系统命令 ping ip -w 280 -n 1(其中ip是变量)根据返回的结果来判断ip是否可通行
如果可通信,将其添加到ip列表中。
public static void main(String[] args) throws IOException {
List<String> result=getAllIp();
System.out.println(result);
}
/**
* 获得内网所有的可通信的ip地址
* @return
* @throws IOException
*/
public static List<String> getAllIp() throws IOException {
InetAddress host=InetAddress.getLocalHost();
String hostAddress=host.getHostAddress();
int pos=hostAddress.lastIndexOf(".");
//获得本机ip的网段
String bigNet=hostAddress.substring(0,pos+1);
List<String> ips=new ArrayList<>();
for (int i=0;i<=225;i++){
String ip=bigNet+i;
Process process = Runtime.getRuntime().exec("ping "+ip+" -w 280 -n 1");
InputStream inputStream=process.getInputStream();
InputStreamReader inputStreamReader=new InputStreamReader(inputStream,"GBK");
BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
String line=null;
String isActive=null;
while((line=bufferedReader.readLine()) != null) {
if(!line.equals("")){
isActive=bufferedReader.readLine().substring(0,2);
break;
}
}
if(isActive.equals("来自")){
ips.add(ip);
}
}
return ips;
}
2)改进
上面的方式是串行执行的,实际运行起来非常慢,请问有没有方式使其很快运行完呢?欢迎留言给出高见!!