java扫描局域网所有活动主机

zyq 2012-12-27 05:33:44
public static void main(String[] args) throws IOException
{
String ip = "192.168.8.";
for (int i = 1 ; i < 256; i++)
{
String host = ip+i;
InetAddress ia = InetAddress.getByName(host);
boolean bool = ia.isReachable(1500);
if (bool)
{
System.out.println("主机: "+host+" 可用");
}

}



}

如上方式实现,速度过慢。
如果用多线程,导致结果错误。
public static void main(String[] args) throws IOException
{
String ip = "192.168.8.";
// for (int i = 1 ; i < 256; i++)
// {
// String host = ip+i;
// InetAddress ia = InetAddress.getByName(host);
// boolean bool = ia.isReachable(1500);
// if (bool)
// {
// System.out.println("主机: "+host+" 可用");
// }
//
// new Thread1(host).start();
// }

for (int i = 1 ; i < 15; i++)
{
String host = ip+i;
new Thread1(host).start();
}


}

static class Thread1 extends Thread
{
String ip = null;

public Thread1(String ip)
{
super();
this.ip = ip;
}

@Override
public void run()
{
super.run();


try
{
InetAddress ia = InetAddress.getByName(ip);
boolean bool = ia.isReachable(1500);
if (bool)
{
System.out.println("主机: "+ip+" 可用");
}
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}



}


}


求优化
要求不能 调用系统的ping来实现
...全文
495 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
引用 5 楼 zhentengai 的回复:
我试了,这个程序可以跑起来的.基本上整个局域网就是1s搞定 你的ip 是不是 192.168.1. 你的例子是 192.168.8.
你这就是一个字2. 哈哈
  • 打赏
  • 举报
回复
撸主,你的问题我完美解决了。
zhentengai 2012-12-28
  • 打赏
  • 举报
回复
我试了,这个程序可以跑起来的.基本上整个局域网就是1s搞定 你的ip 是不是 192.168.1. 你的例子是 192.168.8.
tnjun123456 2012-12-27
  • 打赏
  • 举报
回复
新建一个同步对象管理IP的获取 线程里面做测试是否能够连接的处理
chen_2001 2012-12-27
  • 打赏
  • 举报
回复
通过jni实现ping
yxwd315 2012-12-27
  • 打赏
  • 举报
回复
发UDP广播包不行么?

62,635

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧