Saturday, March 26, 2016

Simple Port Scanner

This program scan the local machine to identify available ports. Scanning range is 0-1024 and can be easily changed by giving the startPort and/or stopPort a new value.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.*;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import javax.swing.*;

public class PortScanner extends JFrame{
    static JTextArea ta=null;
    JScrollPane sp=null;
    
    public PortScanner(){
        super("Port Scanner");
        setSize(400,400);
        setLayout(new BorderLayout());
        
        JButton b=new JButton("Start");
        b.addActionListener(new ButtonHandler());
        add("North",b);
        
        ta=new JTextArea(20,20);
        sp=new JScrollPane(ta);
        add("Center",sp);
        
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }
    
    public static void main(String[] args){
        new PortScanner();
    }
}

class ButtonHandler implements ActionListener{
    public void actionPerformed(ActionEvent e){
        int startPort=0;
        int stopPort=1024; //49151 - 65536
        
        CheckPort[] cp=new CheckPort[(stopPort+1)-startPort];
        
        for(int i=startPort;i<=stopPort;i++){
            cp[i]=new CheckPort(i);
            cp[i].start();
        }
    }
}

class CheckPort extends Thread{        
    int curPort=0;
    
    public CheckPort(int x){
        curPort=x;
    }
    
    public void run(){
        try{
            Socket sok=new Socket("127.0.0.1",curPort);
            PortScanner.ta.append("Port: "+curPort+" (in use)\n");
            sleep(1000);
            sok.close();
        }catch(Exception e){
            PortScanner.ta.append("Port: "+curPort+" (not in use)\n");
        }
    }
}

No comments:

Post a Comment