【第82题】JAVA高级技术-网络编程1(获得内网的所有IP地址)
回城传送–》《JAVA筑基100例》
零、前言
 今天是学习 JAVA语言 打卡的第82天,每天我会提供一篇文章供群成员阅读( 不需要订阅付钱 ),读完文章之后,按解题思路,自己再实现一遍。在小虚竹JAVA社区 中对应的 【打卡贴】打卡,今天的任务就算完成了。
 因为大家都在一起学习同一篇文章,所以有什么问题都可以在群里问,群里的小伙伴可以迅速地帮到你,一个人可以走得很快,一群人可以走得很远,有一起学习交流的战友,是多么幸运的事情。
 学完后,自己写篇学习报告的博客,可以发布到小虚竹JAVA社区 ,供学弟学妹们参考。
 我的学习策略很简单,题海策略+ 费曼学习法。如果能把这100题都认认真真自己实现一遍,那意味着 JAVA语言 已经筑基成功了。后面的进阶学习,可以继续跟着我,一起走向架构师之路。
一、题目描述
在进行网络编程时,有时需要对局域网内的所有主机进行遍历,为此需要获得内网的所有IP地址。
题目实现:获得内网的所有IP地址的小应用。
二、解题思路
创建一个类:GainAllIpFrame,继承JFrame窗体类。
定义一个gainAllIp()方法:用于获得所有IP,并显示在文本域中的方法
定义一个内部类PingIpThread,且是线程类。用于判断给定IP是否为内网IP的线程对象
线程类的执行逻辑是对指定的IP进行 ping 访问
获得本机的IP地址和网段
 InetAddress host = InetAddress.getLocalHost();// 获得本机的InetAddress对象
        String hostAddress = host.getHostAddress();// 获得本机的IP地址
        int pos = hostAddress.lastIndexOf(".");// 获得IP地址中最后一个点的位置
        String wd = hostAddress.substring(0, pos + 1);// 对本机的IP进行截取,获得网段
  
 - 1
 - 2
 - 3
 - 4
 
ping ** 指定的IP地址,获取ping** 结果
 // 获得所ping的IP进程,-w 280是等待每次回复的超时时间,-n 1是要发送的回显请求数
                Process process = Runtime.getRuntime().exec(
                        "ping " + ip + " -w 280 -n 1");
                InputStream is = process.getInputStream();// 获得进程的输入流对象
                InputStreamReader isr = new InputStreamReader(is);// 创建InputStreamReader对象
                BufferedReader in = new BufferedReader(isr);// 创建缓冲字符流对象
                String line = in.readLine();// 读取信息
                while (line != null) {
                    if (line != null && !line.equals("")) {
                        if (line.substring(0, 2).equals("来自")
                                || (line.length() > 10 && line.substring(0, 10)
                                .equals("Reply from"))) {// 判断是ping通过的IP地址
                            pingMap.put(ip, "true");// 向集合中添加IP
                        }
                    }
                    line = in.readLine();// 再读取信息
                }
  
 - 1
 - 2
 - 3
 - 4
 - 5
 - 6
 - 7
 - 8
 - 9
 - 10
 - 11
 - 12
 - 13
 - 14
 - 15
 - 16
 - 17
 
注:本题只适合在window下运行
三、代码详解
引入hutool,pom.xml增加
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-core</artifactId> <version>5.6.5</version> </dependency>
- 1
 - 2
 - 3
 - 4
 - 5
 
GainAllIpFrame
package com.xiaoxuzhu;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
/**
 * Description: 
 *
 * @author xiaoxuzhu
 * @version 1.0
 *
 * <pre>
 * 修改记录:
 * 修改后版本	        修改人		修改日期			修改内容
 * 2022/5/18.1	    xiaoxuzhu		2022/5/18		    Create
 * </pre>
 * @date 2022/5/18
 */
public class GainAllIpFrame extends JFrame {
    private JTextArea ta_allIp;
    static public Hashtable<String, String> pingMap; // 用于存储所ping的IP是否为内网IP的集合
    public static void main(String args[]) {
        GainAllIpFrame frame = new GainAllIpFrame();
        frame.setVisible(true);
    }
    public void gainAllIp() throws Exception {// 获得所有IP,并显示在文本域中的方法
        InetAddress host = InetAddress.getLocalHost();// 获得本机的InetAddress对象
        String hostAddress = host.getHostAddress();// 获得本机的IP地址
        int pos = hostAddress.lastIndexOf(".");// 获得IP地址中最后一个点的位置
        String wd = hostAddress.substring(0, pos + 1);// 对本机的IP进行截取,获得网段
        for (int i = 1; i <= 255; i++) { // 对局域网的IP地址进行遍历
            String ip = wd + i;// 生成IP地址
            PingIpThread thread = new PingIpThread(ip);// 创建线程对象
            thread.start();// 启动线程对象
        }
        Set<String> set = pingMap.keySet();// 获得集合中键的Set视图
        Iterator<String> it = set.iterator();// 获得迭代器对象
        while (it.hasNext()) { // 迭代器中有元素,则执行循环体
            String key = it.next(); // 获得下一个键的名称
            String value = pingMap.get(key);// 获得指定键的值
            if (value.equals("true")) {
                ta_allIp.append(key + "\n");// 追加显示IP地址
            }
        }
    }
    /**
     * Create the frame
     */
    public GainAllIpFrame() {
        super();
        addWindowListener(new WindowAdapter() {
            public void windowOpened(final WindowEvent e) {
                try {
                    gainAllIp();
                    ta_allIp.setText(null);
                } catch (Exception e1) {
                    e1.printStackTrace();
                    ta_allIp.setText(null);
                }
            }
        });
        setTitle("获得内网的所有IP地址");
        setBounds(400, 200, 270, 375);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JScrollPane scrollPane = new JScrollPane();
        getContentPane().add(scrollPane, BorderLayout.CENTER);
        ta_allIp = new JTextArea();
        scrollPane.setViewportView(ta_allIp);
        final JPanel panel = new JPanel();
        getContentPane().add(panel, BorderLayout.NORTH);
        final JButton button_2 = new JButton();
        button_2.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                try {
                    ta_allIp.setText(null);
                    gainAllIp();
                } catch (Exception e1) {
                    e1.printStackTrace();
                    ta_allIp.setText(null);
                    JOptionPane.showMessageDialog(null, "应用程序异常,请再试一次。");
                }
            }
        });
        button_2.setText("显示所有IP");
        panel.add(button_2);
        final JButton button = new JButton();
        button.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                System.exit(0);
            }
        });
        button.setText("退    出");
        panel.add(button);
        pingMap = new Hashtable<String, String>();
    }
    class PingIpThread extends Thread {// 判断给定IP是否为内网IP的线程对象
        public String ip; // 表示IP地址的成员变量
        public PingIpThread(String ip) {// 参数为需要判断的IP地址
            this.ip = ip;
        }
        public void run() {
            try {
                // 获得所ping的IP进程,-w 280是等待每次回复的超时时间,-n 1是要发送的回显请求数
                System.out.println("尝试ping IP:"+ip);
                Process process = Runtime.getRuntime().exec(
                        "ping " + ip + " -w 280 -n 1");
                InputStream is = process.getInputStream();// 获得进程的输入流对象
                InputStreamReader isr = new InputStreamReader(is);// 创建InputStreamReader对象
                BufferedReader in = new BufferedReader(isr);// 创建缓冲字符流对象
                String line =  IoUtil.read(is,"GBK");//CMD获取的值是GBK格式的
                //String line = in.readLine();// 读取信息
                    if (line != null && !line.equals("")) {
                        if (line.indexOf("来自") >0 || line.indexOf("Reply from")>0) {// 判断是ping通过的IP地址
                            pingMap.put(ip, "true");// 向集合中添加IP
                        }
                    }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
  
 - 1
 - 2
 - 3
 - 4
 - 5
 - 6
 - 7
 - 8
 - 9
 - 10
 - 11
 - 12
 - 13
 - 14
 - 15
 - 16
 - 17
 - 18
 - 19
 - 20
 - 21
 - 22
 - 23
 - 24
 - 25
 - 26
 - 27
 - 28
 - 29
 - 30
 - 31
 - 32
 - 33
 - 34
 - 35
 - 36
 - 37
 - 38
 - 39
 - 40
 - 41
 - 42
 - 43
 - 44
 - 45
 - 46
 - 47
 - 48
 - 49
 - 50
 - 51
 - 52
 - 53
 - 54
 - 55
 - 56
 - 57
 - 58
 - 59
 - 60
 - 61
 - 62
 - 63
 - 64
 - 65
 - 66
 - 67
 - 68
 - 69
 - 70
 - 71
 - 72
 - 73
 - 74
 - 75
 - 76
 - 77
 - 78
 - 79
 - 80
 - 81
 - 82
 - 83
 - 84
 - 85
 - 86
 - 87
 - 88
 - 89
 - 90
 - 91
 - 92
 - 93
 - 94
 - 95
 - 96
 - 97
 - 98
 - 99
 - 100
 - 101
 - 102
 - 103
 - 104
 - 105
 - 106
 - 107
 - 108
 - 109
 - 110
 - 111
 - 112
 - 113
 - 114
 - 115
 - 116
 - 117
 - 118
 - 119
 - 120
 - 121
 - 122
 - 123
 - 124
 - 125
 - 126
 - 127
 - 128
 - 129
 - 130
 - 131
 - 132
 - 133
 - 134
 - 135
 - 136
 - 137
 - 138
 - 139
 - 140
 - 141
 - 142
 - 143
 - 144
 - 145
 - 146
 - 147
 - 148
 - 149
 - 150
 - 151
 - 152
 

四、推荐专栏
五、示例源码下载
关注下面的公众号,回复筑基+题目号
筑基82
文章来源: xiaoxuzhu.blog.csdn.net,作者:小虚竹,版权归原作者所有,如需转载,请联系作者。
原文链接:xiaoxuzhu.blog.csdn.net/article/details/125138303
- 点赞
 - 收藏
 - 关注作者
 
            
           
评论(0)