3.Java获得内网网段所有可通信的ip地址

1.实例代码

如果我们想要确定自己所在的局域网的所有用户,我们可以通过这种方式获取:
步骤如下:
首先获取本机地址,截取自己所在的网段
然后调用系统命令 ping ip -w 280 -n 1(其中ip是变量)根据返回的结果来判断ip是否可通行
如果可通信,将其添加到ip列表中。

package InternetCode.Exa3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 获得内网所有ip地址
 */
public class CoreCode {

    private static volatile int num = 0;

    public static void main(String[] args) throws IOException {
        List<String> result=getAllIp();
        System.out.println(result);
    }

    /**
     * 获得内网所有的可通信的ip地址
     * @return
     * @throws IOException
     */
    public static List<String> getAllIp() throws IOException {
        InetAddress host=InetAddress.getLocalHost();
        String hostAddress=host.getHostAddress();
        int pos=hostAddress.lastIndexOf(".");

        //获得本机ip的网段
        String bigNet=hostAddress.substring(0,pos+1);
        List<String> ips= Collections.synchronizedList(new ArrayList<>());
        for (int i=0;i<=225;i++){
            String ip=bigNet+i;
            new Thread(()->{
                try {
                    Process process = Runtime.getRuntime().exec("ping "+ip+" -w 280 -n 1");
                    InputStream inputStream=process.getInputStream();
                    InputStreamReader inputStreamReader=new InputStreamReader(inputStream,"GBK");
                    BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
                    String line=null;
                    String isActive=null;
                    while((line=bufferedReader.readLine()) != null) {
                        if(!line.equals("")){
                            isActive=bufferedReader.readLine().substring(0,2);
                            break;
                        }
                    }
                    if(isActive.equals("来自")){
                        ips.add(ip);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                num++;
            }).start();
        }
        while (num!=225) {}
        return ips;
    }
}

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员小牧之

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值