Reputation: 1437
I'm trying to determine whether a device on a local network has an open port. After reading many opinions, I've been running with the following code:
try
{
Socket s = new Socket();
s.setReuseAddress(true);
SocketAddress sa = new InetSocketAddress(ipAddress,
port);
s.connect(sa,
1000);
return s.isConnected();
}
catch (IOException e)
{
return false;
}
This code works great most of the time. In rare situations after running against thousands of devices, this code will report that port 80 is closed, but then if I try to grab a web page (using Apache HTTPClient) it will work.
Any ideas what could be happening?
Some possible thoughts:
Upvotes: 1
Views: 113
Reputation: 310840
Is the 1000ms timeout insufficient?
Yes.
Is the call to isConnected() unnecessary?
Yes. If it wasn't connected, an exception would have been thrown.
Is setReuseAddress(true) doing anything bad?
It probably isn't doing anything useful at all. If you don't know what it does, what is it doing there?
The main problem with this code is that you're leaking sockets. You need to close the socket in a finally
block.
Of course this kind of predicting the future is inherently fallacious. If you want to know whether the port is listening, try to connect to it and engage in whatever transaction it is that you actually want to do with it, using the same socket.
Upvotes: 1