PortScanner help needed

mrreeds

New member
Joined
Jul 3, 2014
Messages
2
Programming Experience
Beginner
Hello,

I'm currently tryng to create a port scanner to inform our clients for any potential threats.
I'm a beginnner at coding and curretly about 5 days developed this program.
I would like as much help as possible to improve its performance, since right now it showed me some wrong results.
I have included the project in the attachment.
everybody who want to use it, give no warranty, and please dont use it for wrong purpose.

Thanks in advance
 
Last edited by a moderator:
Firstly, I have removed your attachment. If you're going to attach a project then make sure that you delete the `bin` and `obj` files first, because uploading binary files is not allowed.

Secondly, if you have an issue then please ask a question about that issue specifically. Don't just upload a project and say "please help". You say that it shows wrong results. Care to explain what results you get and what results you expect? Upload a project as a last resort only and post the code relevant to a specific issue directly, so we can just read it here instead of having to download, extract and open the project, then trawl through it to work out what we're even looking for. Help us to help you.
 
reason why i include the project is to get the full idea, it has no logical structure and it is easier to see the full code than parts of it. As i said im a beginner at programming.
The false result mean that sometimes it wont detect open port, and when the timeout is few seconds it will show more open ports than there actually are.
And there is a button export XML but i never got it to work. Included the project without bin and obj folders
using System;using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Net.NetworkInformation;
using System.Windows;
using System.Xml;




namespace PortScanner
{
    public partial class portScanner : Form
    {
        private List<int> portList;
        private List<string> ipList;
        private int maxLoading;
        private int avgPing = 0;
        private List<List<string>> finalList = new List<List<string>>();
        private int Counter;
        private bool allPorts=false;
        private int numberOfThreads = 10;
        private int tryTimeout = 150;
        private string MultiThreadBy="port";


        public portScanner()
        {
            for (int i = 0; i < 3; i++)
            {
                this.avgPing = this.avgPing + Convert.ToInt32(new Ping().Send("www.google.com").RoundtripTime);
            }
            this.avgPing = (this.avgPing / 5) + 25;
            InitializeComponent();
            backgroundWorker1.RunWorkerAsync();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            this.startScan.Click += new EventHandler(button9_Click);
        }


        public bool ipCheck(string ip){
            Match match = Regex.Match(ip, @"^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$", RegexOptions.IgnoreCase);
            if (match.Success)
            {
                return true;
            }
            else {
                logOutput.Items.Add("IP Invalid: " + ip);
                return false;
            }
        }


        public List<String> rangeToIps(string range) {
            string[] ipRange = range.Split('-');
            List<string> ips = new List<string>();
            if (ipCheck(ipRange[0]) && ipCheck(ipRange[1]))
            {
                string[] ipStart = ipRange[0].Split('.');
                string[] ipEnd = ipRange[1].Split('.');
                List<int> start = new List<int>();
                List<int> end = new List<int>();


                foreach (string ipNumS in ipStart)
                {
                    start.Add(Int32.Parse(ipNumS));
                }
                foreach (string ipNumE in ipEnd)
                {
                    end.Add(Int32.Parse(ipNumE));
                }
                // int end = Int32.Parse(ipEnd[3]);
                if (start[3] > end[3]) { int temp = start[3]; start[3] = end[3]; end[3] = temp; }


                // Mask max 24
                if (start[2] == end[2])
                {
                    for (int i = start[3]; i <= end[3]; ++i)
                    {
                        ips.Add(start[0] + "." + start[1] + "." + start[2] + "." + i);
                    }
                }


                //mask max 16
                else
                {
                    if (start[2] > end[2]) { int temp = start[2]; start[2] = end[2]; end[2] = temp; temp = start[3]; start[3] = end[3]; end[3] = temp; }
                    for (int i = start[2]; i <= end[2]; ++i)
                    {
                        if (i == start[2])
                        {
                            for (int a = start[3]; a < 256; ++a)
                            {
                                ips.Add(start[0] + "." + start[1] + "." + i + "." + a);
                            }
                        }
                        else if (i == end[2])
                        {
                            for (int b = 1; b <= end[3]; ++b)
                            {
                                ips.Add(start[0] + "." + start[1] + "." + i + "." + b);
                            }
                        }
                        else
                        {
                            for (int c = 1; c < 256; ++c)
                            {
                                ips.Add(start[0] + "." + start[1] + "." + i + "." + c);
                            }
                        }
                    }
                }
            }
            else { logOutput.Items.Add("IP Range Invalid: " + range); }
             return ips;
        }


        public List<int> cleanPort(string[] list){
           // string[] portRange = ports.Split('-');
            List<int> cleaned = new List<int>();
            foreach (string port in list)
            {
                Regex.Replace(port, @"\s+", "");




                try
                {
                    int p = Convert.ToInt32(port);
                    if (p > 0 && p < 65536) { cleaned.Add(p); }
                }
                catch
                {
                    if (port.Contains("-"))
                    {
                        string[] portRange = port.Split('-');
                        try
                        {
                            int start = Convert.ToInt32(portRange[0]);
                            int end = Convert.ToInt32(portRange[1]);
                            if (start > end) { int temp = start; start = end; end = temp; }


                            if (start < end && start > 0 && end < 65536)
                            {
                                for (int i = start; i <= end; ++i)
                                {
                                    cleaned.Add(i);
                                }
                            }else{ logOutput.Items.Add("Port Range Invalid: " + port); }


                        }
                        catch { }


                    }
                    else { 
                         logOutput.Items.Add("Port Invalid: " + port); 
                    }
                }
                
                finally
                {
                   
                }
                


            }


            return cleaned;
        }


        //Clean IPs from input list with ranges to end list (whitspace, duplicates and invalid ip's removed)
        public List<String> cleanIP(string[] list) {
            List<string> cleaned = new List<string>();
            Array.Sort(list);
            foreach (string ip in list)
            {
                Regex.Replace(ip, @"\s+", "");
                if (ipCheck(ip))
                {
                    cleaned.Add(ip);
                }
                else if (ip.Contains('-'))
                {
                    List<string> returnedIPs = rangeToIps(ip);
                    foreach (string returnedIP in returnedIPs)
                    {
                        cleaned.Add(returnedIP);
                    }
                }
            }
            List<string> toReturn = cleaned.Distinct().ToList();
            
            return toReturn;
        }
        
        public bool PortScan(string ip, int port) {
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                IAsyncResult result = socket.BeginConnect(ip, port, null, null);
                bool success = result.AsyncWaitHandle.WaitOne(tryTimeout, true);


                if (success)
                {
                    return true;
                }
                else
                {
                    socket.Close();
                    return false;
                }
            }
            catch {
                socket.Close();
                return false;
            }
        }
        public long PingIP(string IP)
        {


            try
            {
                Ping ping = new Ping();
                PingReply pingReply = ping.Send(IP);


                if (pingReply.Status == IPStatus.Success)
                { return pingReply.RoundtripTime; }
                else { return 99999; }


            }
            catch
            {
                return 99999;
            }
        }
        public bool updateStringListbox(ListBox lstbox){
            var items = lstbox.Items.OfType<string>().GroupBy(item => item).ToList();
            lstbox.Items.Clear();
            foreach (var item in items)
            {
                lstbox.Items.Add(item.Key);
            }
            return true;
        }


        public bool updateIntListbox(ListBox lstbox)
        {
            var items = lstbox.Items.OfType<int>().GroupBy(item => item).ToList();
            lstbox.Items.Clear();
            foreach (var item in items)
            {
                lstbox.Items.Add(item.Key);
            }
            return true;
        }


        private void button1_Click(object sender, EventArgs e)
        {   
            bool check=false;
            foreach(var item in listIp.Items)
                {
                  if(item.ToString() == ipInput.Text)
                  {
                    check=true;
                  }
                }
            if(check){
                logOutput.Items.Add("IP already in list: " + ipInput.Text);
            }else if (ipCheck(ipInput.Text)) {
                
                listIp.Items.Add(ipInput.Text);
            }
        }


        private void button2_Click(object sender, EventArgs e)
        {
            string tempIP = ipRangeStart.Text + "-" + ipRangeEnd.Text;
            foreach (string ip in rangeToIps(tempIP))
            {
                listIp.Items.Add(ip);
            }
        }


        private void button3_Click(object sender, EventArgs e)
        {
            
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";


            DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
            if (result == DialogResult.OK) // Test result.
            {
                string file = openFileDialog1.FileName;
                try
                {
                    string text = File.ReadAllText(file);
                    List<string> lines = new List<string>();


                    using (StreamReader r = new StreamReader(file))
                    {
                        string line;
                        while ((line = r.ReadLine()) != null)
                        {
                            lines.Add(line);
                        }
                    }
                    List<string> insertIPs = cleanIP(lines.ToArray());
                    foreach(string line in insertIPs){
                         listIp.Items.Add(line);
                    }
                    logOutput.Items.Add("IPs Imported From File");
                }
                catch (IOException)
                {
                }
            }
            updateStringListbox(listIp);
        }


        private void button6_Click(object sender, EventArgs e)
        {
            for (int i = listIp.SelectedIndices.Count - 1; i >= 0; i--)
            {
                listIp.Items.RemoveAt(listIp.SelectedIndices[i]);
            }
        }
        


        private void scanComplete()
        {
            
        }


        private void CreateNodes()
        {
            finalList.Clear();
            Counter = 0;
            if(MultiThreadBy == "port"){ // Multithread on port base
                for (int k = 0; k < ipList.Count; k++){
                    List<string> track = new List<string>();
                    long pR = 99999;
                    if (!checkPing.Checked) { pR = PingIP(ipList[k]); }
                    if (pR != 99999 && pR != 0) { track.Add(ipList[k] + " (" + pR.ToString() + "ms)"); }
                    else if (pR == 0) { track.Add(ipList[k] + " (<1ms)"); }
                    else {track.Add(ipList[k]); }
                    
                    if (allPorts) {
                        
                        Parallel.For(1, 65536, new ParallelOptions { MaxDegreeOfParallelism = numberOfThreads }, j =>{
                            if (tryTimeout > 2000) { Random rnd = new Random(); int rndNr = rnd.Next(10, tryTimeout / 10); Thread.Sleep(rndNr); }
                            if (PortScan(this.ipList[k], j)){
                                track.Add(j.ToString());
                            }
                            Interlocked.Add(ref Counter, 1);
                        });
                    }else{
                        Parallel.For(0, this.portList.Count, new ParallelOptions { MaxDegreeOfParallelism = numberOfThreads }, j =>{
                            if (tryTimeout > 2000) { Random rnd = new Random(); int rndNr = rnd.Next(10, tryTimeout / 10); Thread.Sleep(rndNr); }
                            if (PortScan(this.ipList[k], this.portList[j])){
                                track.Add(portList[j].ToString());
                            }
                            Interlocked.Add(ref Counter, 1);
                        });
                    }
                    this.finalList.Add(track);
                }
            }else if(MultiThreadBy == "ip"){ // Multithread on ip base
                Parallel.For(0, ipList.Count, new ParallelOptions { MaxDegreeOfParallelism = numberOfThreads }, k =>{
                    if (tryTimeout > 2000) { Random rnd = new Random(); int rndNr = rnd.Next(10, tryTimeout / 10); Thread.Sleep(rndNr); }
                    List<string> track = new List<string>();
                    long pR = 99999;
                    if (!checkPing.Checked) { pR = PingIP(ipList[k]); }
                    if (pR != 99999 && pR != 0) { track.Add(ipList[k] + " (" + pR.ToString() + "ms)"); }
                    else if (pR == 0) { track.Add(ipList[k] + " (<1ms)"); }
                    else { track.Add(ipList[k]); }


                    //track.Add(ipList[k]);
                    if (allPorts) {
                        for (int j = 1; j < 65536; j++){
                            if (PortScan(this.ipList[k], j)){
                                track.Add(j.ToString());
                            }
                            Interlocked.Add(ref Counter, 1);
                        }
                    }else{
                        for (int j = 0; j < this.portList.Count; j++){
                            if (PortScan(this.ipList[k], this.portList[j])){
                                track.Add(portList[j].ToString());
                            }
                            Interlocked.Add(ref Counter, 1);
                        }
                    }
                    this.finalList.Add(track);
                });
            }
            


        }
        


        private void AddNodes()
        {
            if (this.resultTree.InvokeRequired)
            {
                for (int i = 0; i < finalList.Count; i++)
                {
                    Invoke((MethodInvoker)delegate { resultTree.Nodes.Add(finalList[i][0]); });
                    for (int j = 1; j < finalList[i].Count - 1; j++)
                    {
                        Invoke((MethodInvoker)delegate { resultTree.Nodes[i].Nodes.Add(finalList[i][j]); });
                    }
                }
            }
            finalList.Clear();
        }




        private void button9_Click(object sender, EventArgs e)
        {
            ipList = listIp.Items.Cast<String>().ToList();
            if (radioPortsList.Checked) { allPorts = false; portList = listPorts.Items.Cast<int>().ToList(); maxLoading = ipList.Count * portList.Count; }
            else if (radioPortsDefault.Checked) { allPorts = false; portList = getList("AllDefaultPorts.lst"); maxLoading = ipList.Count * portList.Count; }
            else if (radioPortsCommon.Checked) { allPorts = false; portList = getList("CommonPorts.lst"); maxLoading = ipList.Count * portList.Count; }
            else if (radioPortsAll.Checked) { allPorts = true; maxLoading = ipList.Count * 65535; }
            else
            {
                maxLoading = ipList.Count * portList.Count;
            }
            if (!allPorts)
            {
                if (radioThreadPort.Checked) { MultiThreadBy = "port"; }
                else if (radioThreadIp.Checked) { MultiThreadBy = "ip"; }
                else if (radioThreadAuto.Checked) { if (ipList.Count < portList.Count) { MultiThreadBy = "port"; } else if (ipList.Count > portList.Count) { MultiThreadBy = "ip"; } else { if (ipList.Count < portList.Count) { MultiThreadBy = "ip"; } } }
            }


            if (ipList.Any() && portList.Any() || ipList.Any() && allPorts)
            {
                resultTree.Nodes.Clear();






                listPorts.Enabled = false;
                listIp.Enabled = false;
                listPorts.Enabled = false;
                checkPing.Enabled = false;
                groupBox1.Enabled = false;
                groupBox2.Enabled = false;


                progressBar1.Value = 0;
                countLabel.Enabled = true;
                progressBar1.Maximum = this.maxLoading;
                progressBar1.Visible = true;
                logOutput.Items.Add("IPs To Scan: " + ipList.Count.ToString());
                logOutput.Items.Add("Ports To Scan: " + maxLoading.ToString());
                logOutput.Items.Add("Multithreading: " + MultiThreadBy);
                logOutput.Items.Add("Scan Started: " + DateTime.Now);


                Thread t = new Thread(CreateNodes);
                timer1.Enabled = true;
                t.Start();
            }
            else {
                logOutput.Items.Add("Empty Values Detected!");
            }


        }


        private void button10_Click(object sender, EventArgs e)
        {
            string csvData = "";
            BuildCSV(resultTree.Nodes, ref csvData, 0);


            saveFileDialog1.Filter = "Text File (*.txt)|*.txt | CSV File (*.csv)|*.csv";
            saveFileDialog1.FilterIndex = 1;
            saveFileDialog1.RestoreDirectory = true;
            saveFileDialog1.Title = "Result_Export";


            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                using (Stream myStream = saveFileDialog1.OpenFile())
                {
                    using (StreamWriter wText = new StreamWriter(myStream))
                    {
                        wText.Write(csvData);
                    }
                }
            }
            
        }




        private void button8_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";


            DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
            if (result == DialogResult.OK) // Test result.
            {
                string file = openFileDialog1.FileName;
                try
                {
                    string text = File.ReadAllText(file);
                    List<string> lines = new List<string>();


                    using (StreamReader r = new StreamReader(file))
                    {
                        string line;
                        while ((line = r.ReadLine()) != null)
                        {
                            lines.Add(line);
                        }
                    }
                    List<int> insertPorts = cleanPort(lines.ToArray());
                    foreach (int line in insertPorts)
                    {
                        listPorts.Items.Add(line);
                    }
                    logOutput.Items.Add("Ports Imported From File");
                }
                catch (IOException)
                {
                }
            }
            updateIntListbox(listPorts);
        }


        private void button11_Click(object sender, EventArgs e)
        {
            listIp.Items.Clear();
        }


        private void button12_Click(object sender, EventArgs e)
        {
            listPorts.Items.Clear();
        }


        private void button7_Click(object sender, EventArgs e)
        {
            for (int i = listPorts.SelectedIndices.Count - 1; i >= 0; i--)
            { 
                listPorts.Items.RemoveAt(listPorts.SelectedIndices[i]);
            }
        }
        private void resetForm() {
            progressBar1.Visible = false;
            listPorts.Enabled = true;
            listIp.Enabled = true;
            listPorts.Enabled = true;
            checkPing.Enabled = true;
            groupBox1.Enabled = true;
            groupBox2.Enabled = true;
            timer1.Stop();
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            progressBar1.Value = Counter;
            countLabel.Text = Counter.ToString() + "/" + maxLoading.ToString();
            if (maxLoading == Counter && progressBar1.Value != 0)
            {
                Thread.Sleep(tryTimeout);
                logOutput.Items.Add("Scan Complete: " + DateTime.Now);
                backgroundWorker1.RunWorkerAsync();
                resetForm();
            }
        }


        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
           AddNodes();
        }


        private void button4_Click(object sender, EventArgs e)
        {
            try
                {
                    bool check = false;
                    int port = Convert.ToInt32(portInput.Text);
                    foreach (var item in listPorts.Items)
                    {
                        if (item.ToString() == portInput.Text)
                        {
                            check = true;
                        }
                        else { check = false; }
                    } 
                    if (check) { logOutput.Items.Add("Port already in list: " + portInput.Text); }
                    else if (port > 0 && port < 65536)
                    {
                        listPorts.Items.Add(port);
                    }
                    else {
                        logOutput.Items.Add("Invalid Port: " + portInput.Text);
                    }
                }
                catch
                {
                    logOutput.Items.Add("Invalid Port: " + portInput.Text);
                }
        }








        private void BuildCSV(TreeNodeCollection nodes, ref string csvData, int depth)
        {
            foreach (TreeNode node in nodes)
            {
                csvData = csvData + new String('\t', depth) + node.Text + "\n";
                if (node.Nodes.Count > 0)
                    BuildCSV(node.Nodes, ref csvData, depth+1);
                
            }
        }


        private void button14_Click(object sender, EventArgs e)
        {
            resultTree.CollapseAll();
        }


        private void button15_Click(object sender, EventArgs e)
        {
            resultTree.ExpandAll();
        }




        private void radioButton3_CheckedChanged(object sender, EventArgs e)
        {
            listPorts.Enabled = true;
        }


        private void radioButton6_CheckedChanged(object sender, EventArgs e)
        {
            listPorts.Enabled = false;
           
        }


        private List<int> getList(string fileName) {
            List<string> lines = new List<string>();
            List<int> purePorts = new List<int>();
            try
            {
                string text = File.ReadAllText(fileName);
                


                using (StreamReader r = new StreamReader(fileName))
                {
                    string line;
                    while ((line = r.ReadLine()) != null)
                    {
                        lines.Add(line);
                    }
                }
                purePorts = cleanPort(lines.ToArray());
                return purePorts;


            }
            catch (IOException)
            {
                return purePorts;
            }
        }


        private void radioButton4_CheckedChanged(object sender, EventArgs e)
        {
            listPorts.Enabled = false;


        }


        private void timeoutInput_TextChanged(object sender, EventArgs e)
        {
            try { tryTimeout=Convert.ToInt32(timeoutInput.Text); }
            catch { logOutput.Items.Add("Invalid: " + timeoutInput.Text); }
        }


        private void portRangeAdd_Click(object sender, EventArgs e)
        {
            
                string[] tempPorts = new string[] { portRangeStart.Text + "-" + portRangeEnd.Text };
                foreach (int port in cleanPort(tempPorts))
                {


                    listPorts.Items.Add(port.ToString());
                }
            
        }


    }
}
 

Attachments

  • PortScanner.zip
    20.9 KB · Views: 35
Last edited by a moderator:
When I said that you should post code, I meant just the code relevant to the specific problem. Nobody wants to read all that and posting it all just makes it harder to focus on what's relevant and thus less likely that anyone will try.
 
Back
Top Bottom