我正在尝试创建一个列出本地网络上所有连接设备的功能.我所做的是ping地址空间xxx0到xxx255的任何地址,但它似乎无法正常工作.有人能以某种方式解释或扩展我的代码吗?我从电话(10.0.0.17)和默认网关(10.0.0.138)得到回复.后者甚至不应该存在(事实上我不知道默认网关是什么,但忽略了).我虽然错过了这台电脑的IP.
public ArrayList<InetAddress> getConnectedDevices(String YourPhoneIPAddress) {
ArrayList<InetAddress> ret = new ArrayList<InetAddress>();
LoopCurrentIP = 0;
// String IPAddress = "";
String[] myIPArray = YourPhoneIPAddress.split("\\.");
InetAddress currentPingAddr;
for (int i = 0; i <= 255; i++) {
try {
// build the next IP address
currentPingAddr = InetAddress.getByName(myIPArray[0] + "." +
myIPArray[1] + "." +
myIPArray[2] + "." +
Integer.toString(LoopCurrentIP));
// 50ms Timeout for the "ping"
if (currentPingAddr.isReachable(50)) {
if(currentPingAddr.getHostAddress() != YourPhoneIPAddress){
ret.add(currentPingAddr);
}
}
} catch (UnknownHostException ex) {
} catch …Run Code Online (Sandbox Code Playgroud) 我想在短时间内找到本地网络上服务器的 IP 地址。我知道应用程序在服务器上使用的端口。
我试过这个,但它太慢了。即使我知道 IP,响应时间也太长(每个 IP 大约 4 秒左右)。考虑这种方法,扫描从 10.0.0.0 到 10.0.0.255 的整个子网需要几分钟的时间。
String ip = "10.0.0.45";
try {
InetAddress ping = InetAddress.getByName(ip);
Socket s = new Socket(ping, 32400);
System.out.println("Server found on IP: " + ping.getCanonicalHostName());
s.close();
} catch (IOException e) {
System.out.println("Nothing");
}
}
Run Code Online (Sandbox Code Playgroud)
我可以使用线程,但这仍然会很慢。我已经看到应用程序在那里以毫秒为单位找到 IP。他们怎么做到的?Java代码将不胜感激!