Socket Scanning for Android - java

:) 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;
}

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;
}

Related

Multithreaded data transfer via an array in Java

So, I guess that this has been answered before, but I couldn't find the question, so forgive me.
I have a rather basic chat client-server pair, of which the server is multithreaded to allow for several clients to connect at the same time. The server code looks like this...
private void loop(int port) {
// Opens a port for connections.
ServerSocket serverSocket = null;
Socket clientSocket = new Socket();
try {
serverSocket = new ServerSocket(port);
System.out.println("Server running in port " + port);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Listens for a connection
while (onlineState == true && serverSocket != null) {
if (cur_players < max_players) {
try {
clientSocket = serverSocket.accept();
System.out.println(clientSocket.getInetAddress() + " has connected to the port " + clientSocket.getPort());
cur_players++;
new Thread(new SocketThread( clientSocket, Chat.getOpenSeat() )).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Here, what Chat.getOpenSeat() does is browse an array(boolean seats[]) through for an open spot in the chat buffer array (String buffer[][]) and returns an integer for the spot, then marking it taken. However, when I access the buffer array from the threads, the thread only finds the messages it has added itself. Below is the corresponding code.
toClient = c.poll(bufferSocket); // Retrieves the top-most message from the seat's sub-array,
// then bumps the remaining messages up in the sub-array.
if (toClient != null) {
out.println(toClient); // Sends the message through the Socket.
System.out.println("Message was sent.");
toClient = null;
}
Curiously enough, the threads can access the seats[] array without any trouble, finding the currently active seats and correctly giving all the corresponding sub-arrays their messages. Here's also the bit of code I use to add a new message to the array:
public void offer(String msg) {
for (int seat = 0; seat < Server.max_players; seat++) {
if (seats[seat] == true) {
for (int i = 0; i < 100; i++) {
if (msgBuffer[seat][i] == null) {
msgBuffer[seat][i] = msg;
System.out.println("Message: '" + msg + "' was buffered for the Seat " + seat + ".");
break;
}
}
}
}
}
So, how do I add Strings to an array that is commonly read-write accessible to all of my threads?
Just ask if you need to see more of the code.
Make the array volatile, and it will behave concurrent.
More on volatile: http://www.javamex.com/tutorials/synchronization_volatile.shtml.

How to check if client has disconnected? [duplicate]

This question already has answers here:
Java detect lost connection [duplicate]
(9 answers)
Java socket API: How to tell if a connection has been closed?
(9 answers)
Closed 9 years ago.
I have a java program with Socket. I need to check if client has disconnected. I need a example how to do that. I have researched but I don't understand. So can someone make example code and explane everything.
sorry for bad English
my code:
package proov_server;
//SERVER 2
import java.io.*;
import java.net.*;
class server2 {
InetAddress[] kasutaja_aadress = new InetAddress[1000];
String newLine = System.getProperty("line.separator");
int kliendiNr = 0;
int kilene_kokku;
server2(int port) {
try {
ServerSocket severi_pistik = new ServerSocket(port);
System.out.println("Server töötab ja kuulab porti " + port + ".");
while (true) {
Socket pistik = severi_pistik.accept();
kliendiNr++;
kasutaja_aadress[kliendiNr] = pistik.getInetAddress();
System.out.println(newLine+"Klient " + kliendiNr + " masinast "
+ kasutaja_aadress[kliendiNr].getHostName() + " (IP:"
+ kasutaja_aadress[kliendiNr].getHostAddress() + ")");
// uue kliendi lõime loomine
KliendiLoim klient = new KliendiLoim(pistik,kliendiNr);
// kliendi lõime käivitamine
klient.start();
}
}
catch (Exception e) {
System.out.println("Serveri erind: " + e);
}
}
DataOutputStream[] väljund = new DataOutputStream[1000];
DataInputStream[] sisend = new DataInputStream[1000];
int klient = 0;
int nr;
// sisemine klass ühendusega tegelemiseks
class KliendiLoim extends Thread {
// kliendi pistik
Socket pistik;
// kliendi number
KliendiLoim(Socket pistik2,int kliendiNr) {
nr = kliendiNr;
this.pistik = pistik2;
}
public boolean kontroll(){
try{
System.out.println("con "+pistik.isConnected());
System.out.println("close "+pistik.isClosed());
if(pistik.isConnected() && !pistik.isClosed()){
//System.out.print(con_klient);
return true;
}
}catch(NullPointerException a){
System.out.println("Sihukest klienti pole!!!");
}
kliendiNr --;
return false;
}
public void run() {
try {
sisend[nr] = new DataInputStream(pistik.getInputStream()); //sisend
väljund[nr] = new DataOutputStream(pistik.getOutputStream()); //väljund
}catch (Exception ea) {
System.out.println(" Tekkis erind: " + ea);
}
while(true){
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Sisesta k2sk: ");
String k2sk = null;
k2sk = br.readLine();
/*
String command;
if(k2sk.indexOf(" ") < 0){
command = k2sk;
}else{
command = k2sk.substring(0, k2sk.indexOf(" "));
}
*/
String[] words = k2sk.split("\\s+");
for (int i = 0; i < words.length; i++) {
words[i] = words[i].replaceAll(" ", "");
}
switch(words[0]){
case "suhtle":
if(väljund.length > klient && väljund[klient] != null)
{
väljund[klient].writeUTF("1");
}else{
väljund[klient] = null;
sisend[klient] = null;
System.out.println("Sihukest klienti pole");
}
break;
case "vaheta":
try{
int klinetnr = Integer.parseInt(words[1]);
//if(kontroll(klinetnr) ){
klient = Integer.parseInt(words[1]);
//}
}
catch(NumberFormatException e){
System.out.println("See pole number!!! ");
}
break;
case "kliendid":
if(kliendiNr != 0){
for(int i=1;i <= kliendiNr;i++){
if(kontroll()){
System.out.println("Klient:"+i+" ip: " + kasutaja_aadress[i] );
}else{
System.out.println("Pisi");
väljund[klient] = null;
sisend[klient] = null;
}
}
System.out.println(newLine);
}else{
System.out.println("Kiente pole");
}
break;
}
System.out.println(kliendiNr);
}catch(SocketException a){
System.out.println("Klient kadus");
}
catch(Exception e){
System.out.println(" Viga: " + e);
}
}
}
}
public static void main(String[] args) {
new server2(4321);
}
}
If the client has disconnected properly:
read() will return -1
readLine() returns null
readXXX() for any other X throws EOFException.
The only really reliable way to detect a lost TCP connection is to write to it. Eventually this will throw an IOException: connection reset, but it takes at least two writes due to buffering.
A related thread on Stackoverflow here along with the solution. Basically, the solution says that the best way to detect a client-server disconnect is to attempt to read from the socket. If the read is successfully, then the connection is active.If an exception is thrown during the read there is no connection between the client and the server. Alternatively it may happen that the socket is configured with a timeout value for the read operation to complete. In case, this timeout is exceeded a socket timeout exception will be thrown which can be considered as either the client is disconnected or the network is down.
The post also talks about using the isReachable method - refer InetAddress documentation. However, this method only tells us whether a remote host is reachable or not. This may just one of the reasons for the client to disconnect from the server. You wont be able to detect disconnection due to client crash or termination using this technique.

Java UDP socket client not blocking

I'm trying to code a UDP client to receive packets from a server that is broadcasting on the local network. The problem is the receive method isn't blocking and waiting for a packet to arrive.
Instead, it's receiving null or empty packets.
I've tried to use .setSoTimeout(0), which supposedly will tell the receive to block until it receives a packet, but it doesn't.
Does anyone know how to fix this?
Here's the code:
while (search == true) {
InetAddress addr = InetAddress.getByName("0.0.0.0");
DatagramSocket sock = new DatagramSocket(1355);
sock.setSoTimeout(0);
byte[] recebe = new byte[1024];
sock.setBroadcast(true);
System.out.println("entrou1");
DatagramPacket packet = new DatagramPacket(recebe, recebe.length);
System.out.println("entrou2");
sock.receive(packet);
String info = new String(packet.getData());
System.out.println("tamanho: " + info.length());
if (info.trim().equals("") == false && info != null) {
System.out.println("entrou aqui");
System.out.println("info recebida:" + info + ":fsadfsfs");
String servs[] = info.split("\n");
list1.clear();
servidores.clear();
for (int i = 0; i < servs.length; i++) {
System.out.println("vec: " + servs[i]);
if (servs[i].trim().equals("")) {
System.out.println("break;");
break;
} else {
String aux = servs[i].substring(0, servs[i].lastIndexOf("->"));
System.out.println("aux: " + aux);
list1.add(aux);
servidores.add(servs[i]);
}
}
}
System.out.println("info:\n" + info);
sock.close();
synchronized (obj) {
try {
obj.wait();
} catch (InterruptedException ex) {
Logger.getLogger(AcederPartilhaGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

how to debug a server

I have a server that will be running on another machine and I need to debug with two different machines. Is there a way to virtually debug the server since everything runs ok on my machine but when i put it on another machine everything wrong? I dont have another machine in my possession (I can only host and see results) .
public class fss { public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; boolean listening = true; boolean allowed = true; // int port = Integer.parseInt(args[0]); int port
= 60000;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
System.out.println("Could not transmit on port: " + port);
System.exit(-1);
}
while (listening) {
//Take the ip of the client in number form
allowed = true;
Socket socket = serverSocket.accept();
DataOutputStream outToClient = new DataOutputStream(socket.getOutputStream());
String clientAddress = socket.getRemoteSocketAddress().toString();
clientAddress = clientAddress.substring(1);
for (int i = 0; i < clientAddress.length() - 1; i++) {
if (clientAddress.substring(i, i + 1).equals(":")) {
clientAddress = clientAddress.substring(0, i);
}
}
File f = new File("forbidden.txt");
if (f.exists()) {
BufferedReader forbidden = new BufferedReader(new FileReader("forbidden.txt"));
String addr;
while ((addr = forbidden.readLine()) != null) {
if (Character.isLetter(addr.charAt(0))) {//if the address is in a letter form
addr = InetAddress.getByName(addr).toString();
for (int i = 0; i < addr.length() - 1; i++) {
//System.out.println(addr.substring(i, i + 1));
if (addr.substring(i, i + 1).equals("/")) {
addr = addr.substring(i + 1);
}
}
}
if (clientAddress.equals(addr)) {
allowed = false;
break;
}
}
if (allowed == true) {
new MultiThread(socket).start();
} else {
outToClient.writeBytes("Connection refused" + "\n");
socket.close();
forbidden.close();
}
} else {
new MultiThread(socket).start();
}
}
serverSocket.close();
}
}
You will have to enable debug on server JVM.
This is typically done via following JVM args -
-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8787
You then need to connect to the process using server's IP Address and the above debug port - 8787
One of the answers has already indicated how to enable JDWP on the server. This would require that you have appropriate permissions to open the necessary port as well.
If you do not have this permission, I would humbly suggest using a logger. Your code is completely bereft of any logging calls that would have aided in a scenario where you do not have a lot of control over the runtime environment.
You could start with using the logging framework within Java - java.util.logging, but you'll find log4j or slf4j to be more intuitive.

Java NIO multiple socket connections failing

I have a program that attempts to connect to port 80 on different machines and reports if there is a server running. I am using NIO which therefore uses sockets to do the connection. I do a connect and then poll using finishConnect().
I am getting inconsistent behaviour. Sometimes the program correctly reports that there are web servers running on the various machines that I am scanning. However at other times the connections do not get reported even though there are webservers running on the target machines.
I would understand this if I was using UDP sockets as these are not reliable but I am using a TCP connection that should be reliable i.e no dropped packets.
I need to be able to scan many machines but this inconsistent behaviour exhibits it self even when testing the program with just 4 target IP addresses that all have webservers on port 80.
TIA
Rod
class SiteFinder {
private static final long TIMEOUT = 500;
public void findSites() {
int numSocketChannels = 100;
int socketChannelCounter = 0;
long ipAddressCounter = 0;
boolean done = false;
List<String> allIpAddresses =
IPAddressGenerator.getIPAddresses(170);
SocketChannel[] socketChannelArray =
new SocketChannel[numSocketChannels];
Iterator<String> itr = allIpAddresses.iterator();
while(itr.hasNext()) {
int k;
for (k = 0; k < numSocketChannels && itr.hasNext(); k++) {
String ipAddress = itr.next();
ipAddressCounter++;
if (ipAddressCounter % 50000 == 0)
System.out.println(ipAddressCounter + " at " + new Date());
try {
socketChannelArray[k] = SocketChannel.open();
socketChannelArray[k].configureBlocking(false);
if (socketChannelArray[k].connect(
new InetSocketAddress(ipAddress,80))) {
System.out.println(
"connection established after connect() "
+ ipAddress);
socketChannelArray[k].close();
socketChannelArray[k] = null;
}
} catch (IOException ioe) {
System.out.println(
"error opening/connecting socket channel " + ioe);
socketChannelArray[k] = null;
}
}
while (k < numSocketChannels) {
socketChannelArray[k++] = null;
}
long startTime = System.currentTimeMillis();
long timeout = startTime + TIMEOUT;
connect:
while (System.currentTimeMillis() < timeout) {
//System.out.println("passing");
socketChannelCounter = 0;
for(int j = 0; j < socketChannelArray.length; j++) {
//System.out.println("calling finish connect");
if (socketChannelArray[j] == null) {
++socketChannelCounter;
if (socketChannelCounter == numSocketChannels) {
System.out.println("terminating connection loop");
break connect;
}
continue;
}
try {
if (socketChannelArray[j].finishConnect()) {
/*try {
out.write("connection established after " +
finishConnect()" +
clientChannelVector.elementAt(j).socket().
getInetAddress() + '\n');
out.flush();
} catch (IOException ioe) {
System.out.println(
"error writing to site-list "
+ ioe.getMessage());
}*/
System.out.println(
"connection established after finishConnect()"
+ socketChannelArray[j].socket().
getInetAddress());
socketChannelArray[j].close();
socketChannelArray[j] = null;
}
} catch (IOException ioe) {
System.out.println(
"error connecting from "
+ "clientChannel.finishConnect()");
try {
socketChannelArray[j].close();
} catch (IOException e) {
System.out.println("error closing socket channel");
} finally {
//System.out.println("removing socket channel");
//System.out.println(clientChannelVector.size());
socketChannelArray[j] = null;
}
}
}
}
closeConnections(socketChannelArray);
}
}
private void closeConnections(SocketChannel[] socketChannelArray) {
for (int i = 0; i < socketChannelArray.length; i++) {
if (socketChannelArray[i] == null) {
continue;
}
try {
socketChannelArray[i].close();
//System.out.println(
//"TIME OUT WAITING FOR RESPONSE CLOSING CONNECTION");
} catch (IOException ioe) {
System.out.println(
"error closing socket channel " + ioe.getMessage());
}
}
}
}

Categories

Resources