Java 查询本主机IP所在网段有多少可用IP(*)

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

public class TestSocket {

	public static void main(String[] args) throws IOException{
		InetAddress host = InetAddress.getLocalHost();
		String ip = host.getHostAddress();
		System.out.println(ip);
//		获取ip前三段
		String tIp = ip.substring(0,ip.lastIndexOf(".")+1);
		System.out.println(tIp);
		
		List<String> ips = new ArrayList<>();
		ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10,15,60,TimeUnit.SECONDS,
		 new LinkedBlockingQueue<Runnable>());
		
		threadPool.execute(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				for(int i=1;i<256;i++){
					String testIp = String.format("%s%d",tIp,i);
					long start = System.currentTimeMillis();
					Process p = null;
					try{
						 p = Runtime.getRuntime().exec(" ping "+"testIp");
					}catch(IOException e){
						e.printStackTrace();
					}
				   

					BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
					StringBuilder sb = new StringBuilder();
					String line = null;
					try {
						while((line=br.readLine())!=null){
							if(line.length()!=0)
								sb.append(line+"\r\n");
						}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					long end = System.currentTimeMillis();
					synchronized(ips){
						if(end-start<10000)
							ips.add(testIp);
					}
					System.out.println("已经完成:"+i+"个ip测试");
				}
			}
			
		});

		System.out.println("如下ip地址可以连接:");
		for(int i=0;i<ips.size();i++){
			System.out.println(ips.get(i));
		}
		System.out.println("可用ip地址共有"+ips.size()+"个");
	}
}




  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值