I have made two different programs for port Scanning. Both the programs use Threads but the thread distribution is different. The first one uses single thread for single port, so it is not optimized for memory and time. Here is the code :
import java.net.Socket;
import java.util.Scanner;
import java.lang.Exception;
import java.lang.Thread;
class helper{
public static void main(String []args){
Scanner s= new Scanner(System.in);
int port;
System.out.print("Enter web url :");
String url = s.next();
for(port=0;port<65536;port++){
helper2 h = new helper2(url,port);
h.start();
}
s.close();
}
}
class helper2 extends Thread{
int port;
String url;
helper2(String url,int port){
this.url=url;
this.port=port;
}
private void getStatus(){
try{
Socket skt = new Socket(url,port);
System.out.println(port);
skt.close();
}catch(Exception e){
//Handle Exception here
}
}
public void run(){
getStatus();
}
}
But in the other one I have 256 threads each having performing over 256 ports. It is faster. Here is the other one :
import java.net.Socket;
import java.lang.Thread;
import java.util.Scanner;
import java.lang.Exception;
class helper {
public static void main(String []args){
Scanner s = new Scanner(System.in);
System.out.printf("Enter url :");
String url = s.next();
for(int i=0;i<256;i++){
helper2 h = new helper2(url,256*i);
h.start();
}
s.close();
}
}
class helper2 extends Thread {
int port ;
String url ;
helper2(String url, int port){
this.port=port;
this.url=url;
}
public void run(){
for(int i=0;i<256;i++){
try {
Socket skt = new Socket(url,i+port);
System.out.println(port+i);
skt.close();
} catch (Exception e) {
//TODO: handle exception
// System.out.print('j'); //for debugging
}
}
}
}
Both are working fine when url is given as localhost. But for other url like www.google.com second program does not behave correctly. Sometimes it does not produce any output and sometimes it throws OutOfMemory error and unable to create more threads. Please help.
Socket(String, int)constructor that you're using. Especially at what the first argument represents.