站内搜索: 请输入搜索关键词

当前页面: 开发资料首页Java 专题ping局域网IP的多线程程序

ping局域网IP的多线程程序

摘要: ping局域网IP的多线程程序

</td> </tr> <tr> <td width="439" height="35" valign="top" class="ArticleTeitle"> 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.1true
10.10.1.131true
10.10.1.2true
10.10.1.170true
10.10.1.244true
10.10.1.7true
10.10.1.44true
10.10.1.3true
10.10.1.213true
10.10.1.145true
10.10.1.156true
10.10.1.223true
10.10.1.181true
10.10.1.10true
10.10.1.80true
10.10.1.55true
10.10.1.43true
10.10.1.207true
10.10.1.187true
10.10.1.94true
10.10.1.133true
10.10.1.54true
10.10.1.23true
10.10.1.194true
10.10.1.51true
10.10.1.22true
10.10.1.107true
10.10.1.36true
10.10.1.234true
10.10.1.24true
10.10.1.137true
10.10.1.25true
10.10.1.85true
10.10.1.130true
10.10.1.5true
10.10.1.4true

C:\java>
</td> <td width="245" valign="top" class="ArticleTeitle">

</td> </tr> <tr> <td height="25" colspan="2" valign="top" class="ArticleTeitle">


↑返回目录
前一篇: jdk1.5中访问子进程
后一篇: Interface与Abstract class的异同