Java 网络服务扫描器 [英] Java Network Service Scanner
本文介绍了Java 网络服务扫描器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个类来扫描本地网络以查找将要运行的服务.
I'm trying to write a class that will scan the local network for a service that will be running.
问题是,如果地址不活跃(没有回复),它会在上面挂断 5 秒以上,这是不好的.
The problem is that if the address is not active (no reply) it hangs up on it for 5+ seconds which isn't good.
我想在几秒钟内完成此扫描.任何人都可以提供一些建议吗?
I want to have this scan done in a few seconds. Can anyone offer some advice?
我的代码部分在下面
int port = 1338;
PrintWriter out = null;
BufferedReader in = null;
for (int i = 1; i < 254; i++){
try {
System.out.println(iIPv4+i);
Socket kkSocket = null;
kkSocket = new Socket(iIPv4+i, port);
kkSocket.setKeepAlive(false);
kkSocket.setSoTimeout(5);
kkSocket.setTcpNoDelay(false);
out = new PrintWriter(kkSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
out.println("Scanning!");
String fromServer;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Server here!"))
break;
}
} catch (UnknownHostException e) {
} catch (IOException e) {
}
}
感谢您的回答!这是我为其他人寻找的代码!
Thank you for the answers! Here's my code for anyone else looking for this!
for (int i = 1; i < 254; i++){
try {
System.out.println(iIPv4+i);
Socket mySocket = new Socket();
SocketAddress address = new InetSocketAddress(iIPv4+i, port);
mySocket.connect(address, 5);
out = new PrintWriter(mySocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
out.println("Scanning!");
String fromServer;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Server here!"))
break;
}
} catch (UnknownHostException e) {
} catch (IOException e) {
}
}
推荐答案
您可以尝试通过调用 Socket.connect( address, timeout )
.
You could try connecting to the server explicitly by invoking Socket.connect( address, timeout )
.
Socket kkSocket = new Socket();
kkSocket.bind( null )/ // bind socket to random local address, but you might not need to do this
kkSocket.connect( new InetSocketAddress(iIPv4+i, port), 500 ); //timeout is in milliseconds
这篇关于Java 网络服务扫描器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文