dabocaiqq 2020-08-02 15:51 采纳率: 63.3%
浏览 70
已采纳

Java语言列举所有局域网上打开的计算机的计算机名和ip,并且放在数组中,怎么写

Java语言列举所有局域网上打开的计算机的计算机名和ip,并且放在数组中,怎么写

  • 写回答

1条回答

  • 徐卡丘 2020-08-05 11:38
    关注

    代码如下,需要根据自己情况做调整:

    执行外部命令

    String command = "net view"
    Runtime r = Runtime.getRuntime();
    Process p = r.exec(command);
    BufferedReader br = new BufferedReader(new InputStreamReader(p
    .getInputStream()));

    提取局域网IP
    public static List getIPs()
    {
    List list = new ArrayList();
    boolean flag = false;
    int count=0;
    Runtime r = Runtime.getRuntime();
    Process p;
    try {
    p = r.exec("arp -a");
    BufferedReader br = new BufferedReader(new InputStreamReader(p
    .getInputStream()));
    String inline;
    while ((inline = br.readLine()) != null) {
    if(inline.indexOf("接口") > -1){
    flag = !flag;
    if(!flag){
    //碰到下一个"接口"退出循环
    break;
    }
    }
    if(flag){
    count++;
    if(count > 2){
    //有效IP
    String[] str=inline.split(" {4}");
    list.add(str[0]);
    }
    }
    System.out.println(inline);
    }
    br.close();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    System.out.println(list);
    return list;
    }

    根据IP提取主机名
    public static Map getHostnames(List ips){

        Map<String,String> map = new HashMap<String,String>();
        System.out.println("正在提取hostname...");
        for(String ip : ips){
            String command = "ping -a " + ip;
            Runtime r = Runtime.getRuntime();
            Process p;
            try {
                p = r.exec(command);
                BufferedReader br = new BufferedReader(new InputStreamReader(p
                        .getInputStream()));
                String inline;
                while ((inline = br.readLine()) != null) {
                    if(inline.indexOf("[") > -1){
                        int start = inline.indexOf("Ping ");
                        int end = inline.indexOf("[");
                        String hostname = inline.substring(start+"Ping ".length(),end-1);
                        System.out.println(hostname);
                        map.put(ip,hostname);
                    }
                }
                br.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.println("提取结束!");
        return map;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料