I'm trying to write a code that will return my raspberry's IP when it's on the same network as my computer. The idea is for it to make a broadcast like Samba (Broadcast resolution is the closest to the original NetBIOS mechanism. Basically, a client looking for a service named Trillian will call out "Yo! Trillian! Where are you?", and wait for the machine with that name to answer with an IP address. Source: Samba team)
So here is the code:
public class GetIP {
static String url; //global so I can access it after the threads are finished
public class CheckIP extends Thread {
private String url_test;
public CheckIP(String url_t) {
url_test = url_t;
}
public void run(){
try {
result = getHTML(this.url_test); //result = the response from the GET request to this.url_test
} catch (Exception e) {
}
if(result <is what I want>) {
url = this.url_test
System.out.println("Flag 1");
<I'd like to do something here, preferebly kill all other
threads that are trying to connect to an 'unserved' URL>
}
}
}
public static void main(String[] args) throws Exception{
String ip_partial = <my computer's IP without the last part - ex: "192.168.0." , I'll hide the functions to make it short>;
Thread myThreads[] = new Thread[254];
for (int i = 1; i < 255; i++) {
String url_test="http://"+ip_partial+i+":<port + endpoint>";
GetIP getip = new GetIP ();
myThreads[i] = new Thread(getip.new CheckIP(url_test));
myThreads[i].start();
}
for (int i = 1; i < 254; i++) {
System.out.println("Flag 2");
myThreads[i].join(); //todo add catch exception
}
}
}
I can see flag 1, and I did print the first 'for' so I know there are 254 threads being created, however I cannot see flag 2. It never shows, nomatter how long I wait. Any ideas why?
The problem with your code is java.lang.ArrayIndexOutOfBoundsException:
You are executing the loop till 254th index, whereas your array size itself is 254 which means the index present is 253 since java starts it's indexing from 0.
The first loop should also run the same no of iteration as your second loop.
for (int i = 1; i < 254; i++) {
/\
||
||
||
This should not be 255 else you'll get OutOfBounds Exception.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With