搜索局域网里的所有IP地址

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.StringTokenizer;
import java.util.Vector;

public class SearchIP {
	public static void main(String[] args) {
		SearchIP.getAllOnLineIP();
	}
	/*
	 * 设计思路: 怎样实现搜索其实是serversocket搜端口,即客户端向指定IP的端口发送数据(使用的是arp -a命令),
	 * 如果有数据返回,说明这个IP的端口开启了服务器(如cs的服务器), 而服务器端则是有发数据则返回。
	 * 你可以用下面的方法搜索到所有的IP,然后向全部IP发送数据, 然后等一段时间(如3秒)检查发回数据的信息
	 */
	public static  InetAddress[] getAllOnLineIP() {
		/*
		 * the Vector class implements a growable array of objects,like an
		 * array, the size of a Vector can grow of shrink as needed to
		 * accommodate adding or removing items after the vector has been
		 * created
		 */		
		Vector<InetAddress> v = new Vector<InetAddress>();  //用于存放InetAddress类型的IP地址
		try {
			//Runtime:the current runtime can be obtained from the getRuntime method.
			//getRuntime: returns the Runtime object associated with the current application.
			//exec:Exectues the specified String command in a separate process.
			Process process = Runtime.getRuntime().exec("arp -a");
			InputStreamReader input = new InputStreamReader(process.getInputStream());
			BufferedReader br = new BufferedReader(input);
			String temp = "";
			//这两句为描述信息,为空行,所以应该将单独处理
			System.out.println(br.readLine()); //输出为空行
			br.readLine();
			br.readLine(); //读取一行IP数据
			while((temp=br.readLine())!=null){
				StringTokenizer token = new StringTokenizer(temp);
				InetAddress id = InetAddress.getByName(token.nextToken());
				v.add(id);
				System.out.println(id);
			}
			v.add(InetAddress.getLocalHost()); //获取自己主机的IP地址
			
			process.destroy();
			br.close();
			input.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		int cap = v.size();
		InetAddress[] addrs = new InetAddress[cap];
		for(int i = 0;i<cap;i++){
			addrs[i] = (InetAddress)v.elementAt(i);
			System.out.println(addrs[i]);
		}
		return addrs;
	}
}

输出结果为:

/172.16.26.3
/172.16.26.33
/172.16.26.71
/172.16.26.98
/172.16.26.100
/172.16.26.101
/172.16.26.153
/172.16.26.181
/172.16.26.188
/172.16.26.215
/172.16.26.254
/172.16.26.255
/224.0.0.22
/224.0.0.252
/229.255.255.250
/239.255.255.250
rdm-PC/172.16.26.34
这是改编自网上的代码,初学者,所有有很多都不懂。。。。

昨天晚上跟寝室的师兄交流到了凌晨01.30,两个多小时,受益匪浅。。。

现将感想发表于下:

学习还是要给自己压力,不能拖拖踏踏的,给自己一个时间限制,比如我要三个月把java学精通。

多跟导师交流,多跟周边的师兄师姐交流,借鉴他们的优秀的学习方法。

多做项目。

每做一个项目或每过一段时间都要及时的总结,并以文档的方式写出来。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值