我已经将我的代码精简为最基本的内容,它非常简单明了。
我有以下代码:
public ArrayList<Node> getNodes() throws IOException
{
ArrayList<Node> nodes = new ArrayList<Node>();
StringBuffer root = new StringBuffer(InetAddress.getLocalHost().getHostAddress());
while(!root.toString().endsWith("."))
root.deleteCharAt(root.length() - 1);
//^^ this code gets the ip, for ex 127.0.0.1, and trims the last number, to make it
//^^ 127.0.0. <-- see the trailing 0
for(int host = 0;host < 256; host++)
{
InetAddress address = InetAddress.getByName(root.toString() + host);
try
{
if(address.isReachable(500)) // pings the address
nodes.add(new Node(address.getHostAddress(), false));
}catch(Exception e){new Node(address.getHostAddress(), true);}
}
return nodes;
}
这是节点类,非常简单:
public class Node
{
public Node(String address, boolean restricted)
{
this.address = address;
this.restricted = restricted;
}
public String address;
public boolean restricted;
}
这是我的主要代码,它执行getNodes():
case 1:
System.out.println("Searching for nodes...");
NodeDetector node = new NodeDetector(); // this is the class
//where getNodes resides
ArrayList<Node> nodes = node.getNodes();
Iterator<Node> it = nodes.iterator();
while(it.hasNext())
{
System.out.println("Node: "+it.next().address);
}
System.out.println("stopped searching for nodes...");
break;
这是我的输出:
Searching for nodes...
Node: 00.00.17.99
Node: 00.00.17.100
Node: 00.00.17.149
Node: 00.00.17.150 <-- this is my computer
Node: 00.00.17.154
Node: 00.00.17.156
Node: 00.00.17.254
stopped searching for nodes...
现在问题来了
我在手机上下载了一个网络节点发现工具,它至少可以找到 5 个节点。我尝试更改超时值,但仍然没有运气。当我 ping 一个地址时,该地址是用网络工具在手机上而不是在我的计算机上找到的,ping 会立即被接收并返回。这个问题很相似,它对我有所帮助,但我仍然卡住了:
- 如何从Windows进行真正的Java ping?
我正在Mac上运行我的工具,它似乎可以很好地拾取其他Mac,iPod和路由器,但仅此而已。为什么我的程序无法检测到网络上的其他设备?
这是我从手机上的网络工具获得的输出:
00.00.17.99 <-- SMC Networks *
00.00.17.100 <-- XEROX *
00.00.17.133 <-- My Phone (Android)
00.00.17.134 <-- Intel
00.00.17.142 <-- Apple
00.00.17.149 <-- Apple *
00.00.17.150 <-- Apple * <-- this is my computer
00.00.17.154 <-- Apple *
00.00.17.155 <-- Intel
00.00.17.156 <-- Apple *
00.00.17.158 <-- Motorola Mobility
00.00.17.254 <-- Netopia *
我在
手机上的工具与我在计算机上编写的工具一致的地方放了一个 *。我已经运行了几次此测试,每次在计算机和手机上都获得相同的输出,在测试期间没有在网络中添加或删除任何设备。
经过几天的研究,我发现这是一个不错的解决方案:
try
{
Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 -W 250 " + address.getHostAddress());
int returnVal = p1.waitFor();
boolean reachable = (returnVal==0);
if(reachable)
nodes.add(new Node(address.getHostAddress(), false));
}catch(Exception e)
{
new Node(address.getHostAddress(), true);
}
唯一的缺点是它依赖于系统。我将是唯一一个使用此工具的人,所以这对我来说真的没有问题。