Java-获得内网所有的IP地址

我们这里获取的内网IP    一般是192.168.X,X的IP地址  (在自己的电脑上运行)

原理就是:首先获得本机的IP地址,然后ping网络的IP地址,通过输入刘对象读取所ping的结果,并判断是否为内网的IP地址。

我看了书上描述的方法后,看起来的确容易,可是,真正操作起来,发现了许多的问题,甚至都无法得到结果,其他人的所发的文章大同小异都输出不了

我搞了几天后终于找到了原因


最主要的原因就是-----线程所得结果跟不上整个程序的速度

具体一点就是,当你的线程所进行的操作不是一般的操作,是ping操作,这个操作比如你在cmd中 写入

ping 192.168.253.3 -w 1000 -n 1


很清楚,他是需要等一段时间才能得到返回值的,不像是平常的程序,走一遍就结束了。

所以,这里的线程 对192.168.253.1~192.168.253.255中的每一个ip ping的时候需要等待他的回复,等待他的一个返回值才行------换句话说,就是一个一个慢慢来


关键的code就是在线程类中的

try {
            thread.join();
            } catch (InterruptedException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
            } 

 通过baidu这个join()方法-------解释为 主线程等待子线程的终止。

最大的困惑也说完了,亲测下面的是可以运行的,大家来造作啊,快活啊。


我们可以先打开cmd,先输入 ipconfig 查到自己的IP是多少,这里可能会有两个IP地址,一个是无线网,一个是本地局域网,


内网当然是指的192.168 开头的这个私有地址,我们的笔记本用的无线上网的话,我这里是校园网,172开始的,所以先不讨论之。


一个类 +一个内部方法+一个内部类(线程)

这个是主类

public class GainAllIPFrame extends JFrame{
	public static JFrame frame;
	public static JPanel panel;
	public static JButton btn_showUp,btn_exit;
	public static JScrollPane scroll;
	public static JTextArea area_IP;
	public static String ip;
	public static String gainAllFrame="GainAllFrame";
	
	public static  Map<String, String> pingMap = new HashMap<String, String>(); 
	public static void main(String[] args){
		
		frame=new JFrame();
		panel=new JPanel();
		area_IP=new JTextArea();
		scroll=new JScrollPane();
		btn_showUp=new JButton();
		
		area_IP.setSize(400, 800);
		//设置滚动布局
		scroll.setWheelScrollingEnabled(true);
		scroll.setViewportView(area_IP);
		Dimension d=new Dimension();
		d.setSize(400, 800);
		//对这个滑动窗口进行大小设置,但是在JScrollPane类中并没有发现这个setPreferredSize()的方法
		//但是却在JComponent类中发现了他,也就是说继承他的子类可以使用它父类的方法所以得以使用
		scroll.setPreferredSize(d); 
		
		
		btn_showUp.setBounds(50, 20, 100, 50);
		btn_showUp.setText("显示所有IP");
		btn_showUp.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO 自动生成的方法存根
				try {
					area_IP=gainAllIp();
					System.out.println(gainAllFrame);
					
				} catch (IOException e1) {
					// TODO 自动生成的 catch 块
					e1.printStackTrace();
				}
			}
		});
		
		
		//auto_Button(panel, btn_showUp, 50, 20, 100, 50, "显示所有IP",1);
		panel.add(btn_showUp);
		panel.add(scroll);
		frame.add(panel);
		frame.setSize(500, 1000);
		frame.setVisible(true);
		
	} <span style="font-family: Arial, Helvetica, sans-serif;">}</span>


以下是我的获取IP的方法,获取完毕后返回一个JTextArea

public static JTextArea gainAllIp() throws IOException{
		
		GainAllIPFrame allIPFrame=new GainAllIPFrame();
		PingIpThread thread=null;
		allIPFrame.gainAllFrame="1111111111111";
		InetAddress host=InetAddress.getLocalHost();	//获得本机的InetAddress对象 ,回送IP地址
		String hostAddress=host.getHostAddress();		//同样获得IP(以文本表现形式)
		int pos=hostAddress.lastIndexOf(".");			//获得IP地址中最后一个点的位置
		String wd=hostAddress.substring(0,pos+1);
		System.out.println("\n"+"wd"+wd);//对本机的IP地址进行街区,get the network segment
		System.out.println("11111");
		for (int i = 0; i < 8; i++) {
            String ip=wd+i;
             thread=allIPFrame.new PingIpThread(ip);
            System.out.println("ip:"+ip);
            thread.start();
            try {
            	thread.join();
            } catch (InterruptedException e) {
            	// TODO 自动生成的 catch 块
            	e.printStackTrace();
            }  
            pingMap=thread.getMap();
            System.out.println("\n有没有有没有有没有有没有有没有有没有有没有"+thread.getMap());
    		
    		
    		Set<String> set=pingMap.keySet();
    		Iterator<String> it=set.iterator();		//获得迭代器对象
    		
    		while(it.hasNext()){
    			String key=it.next();
    			String value=pingMap.get(key);
    			System.out.println("\n"+"4444"+value);
    			if(value.equals("true")){
    				area_IP.append(key+"\n");
    				System.out.println("\n"+"4444"+key);
    			}
    		}
    		
        }	
		
		
		
		return area_IP;
		
	}

以下这个类是线程类,用来进行ping操作

class PingIpThread extends Thread{
		public String ip;
		public  Map<String, String> map = new HashMap<String, String>(); 
		PingIpThread (String ip){
			this.ip=ip;
		}
		public Map<String, String> getMap(){
			return map;
		}
		
		public void run() {
				try {
					
					System.out.println("\n"+"第一行");
					//获得ping的IP进程,-w 280是等待每次回复的超时时间,-n 1是要发送的回显请求数
					Process process=Runtime.getRuntime().exec("ping "+ip+" -w 1000 -n 1");
					System.out.println("\n"+"第二行");
					InputStream is=process.getInputStream();	//数据流
					System.out.println("\n"+"is:"+is);
					InputStreamReader isr=new InputStreamReader(is);	//数据流读取
					System.out.println("\n"+"isr:"+isr);
					BufferedReader in=new BufferedReader(isr);	//缓冲流
					System.out.println("\n"+"in:"+in);
					String line=in.readLine();   //缓存中读取       
					System.out.print("line:"+line);
					if(line.equals(null))System.out.println("null");
					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地址
								map.put(ip,"true");						//向集合中添加IP地址
								System.out.println("!null"+map);
							}
						}
						line=in.readLine();
						System.out.println("!null"+line);
					}
					System.out.println("!line"+line);
				} catch (IOException e) {
					// TODO: handle exception
				}
			}

		
	}

PS:上面getAllIP()方法中写的变量i是0-8,为什么会有内网IP,我这里是开着360WIFI 给舍友用的,蓝瘦香菇。所以会占用内网的IP,你要是没有其他终端的话,应该只有你的192.168.253.1了。


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值