依据之前的博客 在知道如何利用Java得出本机IP地址及使用ping判断一个地址是否能够到达
以下是结合两者对判断本网段有多少可用的ip地址 1到255
代码示例:
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class TestSocket {
public static void main(String[] args) throws IOException {
InetAddress in=InetAddress.getLocalHost();
String str=in.getHostAddress();
System.out.println("本机的IP地址"+str);
String str2=str.substring(0,str.lastIndexOf(".")+1);
ThreadPoolExecutor tpe=new ThreadPoolExecutor(100,200,5,TimeUnit.SECONDS,new LinkedBlockingDeque<>());
for (int i=1;i<=255;i++){
final int j=i;
tpe.execute(new Runnable() {
@Override
public void run() {
Process p;
try{
p=Runtime.getRuntime().exec("ping "+str2+j);
BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream(),"GBK"));
String temp=null;
boolean tag=false;
while((temp=br.readLine())!=null)
{
if(temp.contains("TTL"))
{
tag=true;
break;
}
}
if(tag)
{
System.out.println("it's can be uesd:"+str2+j);
}
}catch(IOException e)
{
System.out.println("gan!");
e.printStackTrace();
}
}
});
}
}
}
利用Java自带的线程池 缓存流里实例化输入流对象一行行读取数据
|