Loading

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;
    }
}

  

 
posted @ 2021-10-06 17:21  文牧之  阅读(147)  评论(2)    收藏  举报  来源