TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
import java.io.*;
import java.util.*;
public class Ip{
static public HashMap ping; //ping 后的结果集
//当前线程的数量, 防止过多线程摧毁电脑
static int threadCount = 0;
public Ip() {
ping = new HashMap();
}
public void Ping(String ip) throws Exception{
//最多30个线程
while(threadCount>30)
Thread.sleep(50);
threadCount +=1;
PingIp p = new PingIp(ip);
p.start();
}
public void PingAll() throws Exception{
for(int i=1;i<=255;i++){ //对所有局域网Ip
String iip="10.10.1."+i;
Ping(iip);
}
//等着所有Ping结束
while(threadCount>0)
Thread.sleep(50);
}
public static void main(String[] args) throws Exception{
Ip ip= new Ip();
ip.PingAll();
java.util.Set entries = ping.entrySet();
Iterator iter=entries.iterator();
String k;
while(iter.hasNext()){
Map.Entry entry=(Map.Entry)iter.next();
String key=(String)entry.getKey();
String value=(String)entry.getValue();
if(value.equals("true"))
System.out.println(key+"-->"+value);
}
}
class PingIp extends Thread{
public String ip; // IP
public PingIp(String ip){
this.ip=ip;
}
public void run(){
try{
Process p= Runtime.getRuntime().exec ("ping "+ip+ " -w 300 -n 1");
InputStreamReader ir = new InputStreamReader(p.getInputStream());
LineNumberReader input = new LineNumberReader (ir);
//读取结果行
for (int i=1 ; i<7; i++)
input.readLine();
String line= input.readLine();
// System.out.println("OK!!"+ip+"--OUT:-->"+line);
if (line.length()<17 || line.substring(8,17).equals("timed out"))
ping.put(ip,"false");
else
ping.put(ip,"true");
//线程结束
threadCount -= 1;
}catch (IOException e){}
}
}
}
程序运行结果:
C:java>java Ip
10.10.1.1-->true
10.10.1.131-->true
10.10.1.2-->true
10.10.1.170-->true
10.10.1.244-->true
10.10.1.7-->true
10.10.1.44-->true
10.10.1.3-->true
10.10.1.213-->true
10.10.1.145-->true
10.10.1.156-->true
10.10.1.223-->true
10.10.1.181-->true
10.10.1.10-->true
10.10.1.80-->true
10.10.1.55-->true
10.10.1.43-->true
10.10.1.207-->true
10.10.1.187-->true
10.10.1.94-->true
10.10.1.133-->true
10.10.1.54-->true
10.10.1.23-->true
10.10.1.194-->true
10.10.1.51-->true
10.10.1.22-->true
10.10.1.107-->true
10.10.1.36-->true
10.10.1.234-->true
10.10.1.24-->true
10.10.1.137-->true
10.10.1.25-->true
10.10.1.85-->true
10.10.1.130-->true
10.10.1.5-->true
10.10.1.4-->true
C:java> |
|