判断本网段有多少可用的ip地址

为了提高效率,使用多线程方式同时ping。 但是如果开启255个线程,又会因为网络端口太拥挤,会被判定为无法ping通。
所以本例使用java自带线程池,线程池的连接数还不能太大,启动了15个线程。 

等待所有的线程结束后打印出ping通了的ip地址。

 

 

package AtomicInteger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class TestSocket {

public static void main(String[] args) throws IOException, InterruptedException {
InetAddress host = InetAddress.getLocalHost();
String ip = host.getHostAddress();
String ipRange = ip.substring(0, ip.lastIndexOf('.'));
System.out.println("本机ip地址:" + ip);
System.out.println("网段是: " + ipRange);

final List<Object> ips = Collections.synchronizedList(new ArrayList<>());
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 15, 60, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>());
final AtomicInteger number = new AtomicInteger();
for (int i = 0; i < 255; i++) {
final String testIP = ipRange + "." + (i + 1);
threadPool.execute(new Runnable() {
@Override
public void run() {
boolean reachable = isReachable(testIP);
if (reachable)
// System.out.println("找到可连接的ip地址:" + testIP);
ips.add(testIP);

synchronized (number) {
System.out.println("已经完成:" + number.incrementAndGet() + " 个 ip 测试");
}
}

});

}

// 等待所有线程结束的时候,就关闭线程池
threadPool.shutdown();
//等待线程池关闭,但是最多等待1个小时
if (threadPool.awaitTermination(1, TimeUnit.HOURS)) {
System.out.println("如下ip地址可以连接");
for (Object theip : ips) {
System.out.println(theip);
}
System.out.println("总共有:" + ips.size() + " 个地址");

}
}

private static boolean isReachable(String ip) {
try {
boolean reachable = false;

Process p = Runtime.getRuntime().exec("ping -n 1 " + ip);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
if (line.length() != 0)
sb.append(line + "\r\n");
}

//当有TTL出现的时候,就表示连通了
reachable = sb.toString().contains("TTL");
br.close();
return reachable;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}

}

转载于:https://www.cnblogs.com/chinaifae/p/10194753.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值