Reputation: 21
:) I'm trying to make an Android app which will scan an entire network for a specific open port. I am using Android Studio (Windows) and the emulator. I am able to scan the network for 90 seconds before my program stops running. I don't receive any logcat errors and I lose the stack and program counter in the debugger. I cannot restart the program without first restarting the emulator. It looks like I lose any connection I had to the emulator.
I should also mention that removing the socket connect line results in the task running indefinitely. Has anyone experienced this kind of time out before?
Any pointers in the right direction would be much appreciated!!
Jenny
private class getNetworkState extends AsyncTask<Integer, Integer, Integer> {
@Override
protected Integer doInBackground(Integer... params) {
for (int subnet2 = 216; subnet2 < 220; subnet2++)
{
for (int subnet = 0; subnet < 255; subnet++)
{
// open a tcp socket
String server = String.format("192.168.%d.%d", subnet2, subnet);
Socket socket = new Socket();
try
{
socket.connect(new InetSocketAddress(server, port), timeOut);
System.out.println("Network state of " + server + " == " + socket.isConnected());
socket.close();
}
catch (Exception e)
{
System.out.println("Network state of " + server + " == " + e);
}
}
}
return 1;
}
Upvotes: 2
Views: 2240
Reputation: 3717
How often are you seeing exceptions in socket.connect(...)? The way the code exists, failed connects will throw an Exception and the socket will not be closed.
I think a better practice would be to close the socket in a finally block. If the cause of your problems is a ton of open sockets, this might help clear up the issue.
private class getNetworkState extends AsyncTask<Integer, Integer, Integer> {
@Override
protected Integer doInBackground(Integer... params) {
for (int subnet2 = 216; subnet2 < 220; subnet2++)
{
for (int subnet = 0; subnet < 255; subnet++)
{
// open a tcp socket
String server = String.format("192.168.%d.%d", subnet2, subnet);
Socket socket = new Socket();
try
{
socket.connect(new InetSocketAddress(server, port), timeOut);
System.out.println("Network state of " + server + " == " + socket.isConnected());
}
catch (Exception e)
{
System.out.println("Network state of " + server + " == " + e);
} finally {
socket.close();
}
}
}
return 1;
}
Upvotes: 1