C# skaner portów - > Przekształcenie Konsoli na Formę

0

Witam. Pisze na zaliczenie pod-aplikacje do skanowania portów tzn. próbuje przekształcić aplikacje konsolową na aplikację okienkową. Program okienkowy nie działa do końca, ponieważ zachowuje się jakby nie rozróżniał portów otwartych od zamkniętych. Chciałem wykorzystać do tego wątki jednakże nie za bardzo wiem jak przekształcić kod formy tak by dane z interfejsu aktualizowały się a liczenie odbywało się w osobnym wątku.
**
Tutaj kod konsoli:**

usingSystem.Collections.Generic;
using System.Linq;
using System;
using System.Text;
using System.Net;
using System.Threading;
using System.Net.Sockets;
 
namespace PortScanner
{
    class Program
    {
        static bool stop = false;
        static int startPort;
        static int endPort;
 
        static List<int> openPorts = new List<int>();
 
        static object consoleLock = new object();
 
        static int waitingForResponses;
 
        static int maxQueriesAtOneTime = 100;
 
        static void Main(string[] args)
        {
        begin:
            Console.WriteLine("Podaj docelowy adres IP:");
            string ip = Console.ReadLine();
 
            IPAddress ipAddress;
 
            if (!IPAddress.TryParse(ip, out ipAddress))
                goto begin;
 
        startP:
 
            Console.WriteLine("Podaj port początkowy:");
            string sp = Console.ReadLine();
 
            if (!int.TryParse(sp, out startPort))
                goto startP;
 
        endP:
 
            Console.WriteLine("Podaj port końcowy i rozpocznij skanowanie:");
            string ep = Console.ReadLine();
 
            if (!int.TryParse(ep, out endPort))
                goto endP;
 
            Console.WriteLine("");
            Console.WriteLine("");
            Console.WriteLine("");
            Console.WriteLine("");
 
            Console.WriteLine("Naciśnij dowolny klawisz , aby zatrzymać skanowanie...");
 
            Console.WriteLine("");
            Console.WriteLine("");
 
            ThreadPool.QueueUserWorkItem(StartScan, ipAddress);
 
            Console.ReadKey();
 
            stop = true;
 
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
 
        static void StartScan(object o)
        {
            IPAddress ipAddress = o as IPAddress;
 
            for (int i = startPort; i < endPort; i++)
            {
                lock (consoleLock)
                {
                    int top = Console.CursorTop;
 
                    Console.CursorTop = 7;
                    Console.WriteLine("Scanning port: {0}    ", i);
 
                    Console.CursorTop = top;
                }
 
                while (waitingForResponses >= maxQueriesAtOneTime)
                    Thread.Sleep(0);
 
                if (stop)
                    break;
 
                try
                {
                    Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 
                    s.BeginConnect(new IPEndPoint(ipAddress, i), EndConnect, s);
 
                    Interlocked.Increment(ref waitingForResponses);
                }
                catch (Exception)
                {
 
                }
            }
        }
 
        static void EndConnect(IAsyncResult ar)
        {
            try
            {
                DecrementResponses();
 
                Socket s = ar.AsyncState as Socket;
 
                s.EndConnect(ar);
 
                if (s.Connected)
                {
                    int openPort = Convert.ToInt32(s.RemoteEndPoint.ToString().Split(':')[1]);
 
                    openPorts.Add(openPort);
 
                    lock (consoleLock)
                    {
                        Console.WriteLine("Connected TCP on port: {0}", openPort);
                    }
 
                    s.Disconnect(true);
                }
            }
            catch (Exception)
            {
 
            }
        }
 
        static void IncrementResponses()
        {
            Interlocked.Increment(ref waitingForResponses);
 
            PrintWaitingForResponses();
        }
 
        static void DecrementResponses()
        {
            Interlocked.Decrement(ref waitingForResponses);
 
            PrintWaitingForResponses();
        }
 
        static void PrintWaitingForResponses()
        {
            lock (consoleLock)
            {
                int top = Console.CursorTop;
 
                Console.CursorTop = 8;
                Console.WriteLine("Waiting for responses from {0} sockets       ", waitingForResponses);
 
                Console.CursorTop = top;
            }
        }
    }
 
} 

**
Natomiast tutaj kod formy, który do tej pory udało mi się skleić. **

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Sockets;
 
namespace MassMeil
{
    public partial class SkanerPortow : Form
    {
        public SkanerPortow()
        {
            InitializeComponent();
            Komunikaty();
        }
        static List<int> openPorts = new List<int>();
        static bool stop = false;
        static int StartPort;
		static int KoniecPort;
        static object consoleLock = new object();
        static int waitingForResponses;
        static int maxQueriesAtOneTime = 100;
 
        private void Komunikaty()
        {
             Logtxt.AppendText("Wprowadź IP oraz numery Portów i Rozpocznij Skanowanie");
        }
        public void EndConnect(IAsyncResult ar)
        {
            try
            {
                DecrementResponses();
 
                Socket TcpScan = ar.AsyncState as Socket;
 
                TcpScan.EndConnect(ar);
 
                if (TcpScan.Connected)
                {
                    int openPort = Convert.ToInt32(TcpScan.RemoteEndPoint.ToString().Split(':')[1]);//
 
                    openPorts.Add(openPort);
 
                    lock (consoleLock)
                    {
                        Logtxt.AppendText("Connected TCP on port: {0}" + openPort);
                    }
 
 
                    TcpScan.Disconnect(true);
                }
            }
            catch (Exception)
            {
 
            }
        }
		public void SkanStart_Click(object sender, EventArgs e)
        {
            Komunikaty();
            funkcje();
            Skan(sender);
 
		}
        public void funkcje()
        {
           /*
        begin1:
            string ip = Host.Text;
            IPAddress ipAddress;
            if (!IPAddress.TryParse(ip, out ipAddress))
                goto begin1;
 
        begin2:
            string sp = numericUpDown1.ToString();
 
            if (!int.TryParse(sp, out StartPort))
                goto begin2;
 
        begin3:
            string ep = numericUpDown2.ToString();
 
            if (!int.TryParse(ep, out KoniecPort))
                goto begin3;
 
 
            ThreadPool.QueueUserWorkItem(Skan, ipAddress);
            stop = true;*/
        }
        public void Skan(object sender)
        {
            IPAddress ipAddress = sender as IPAddress;
			StartPort = Convert.ToInt32(numericUpDown1.Value);
			KoniecPort = Convert.ToInt32(numericUpDown2.Value);
			StatusSkanu.Value = 0;
			StatusSkanu.Maximum = KoniecPort - StartPort + 1;
			Cursor.Current = Cursors.WaitCursor;
			for (int i = StartPort; i <= KoniecPort; i++)
			{
                while (waitingForResponses >= maxQueriesAtOneTime)
                    Thread.Sleep(0);
                if (stop)
                    break;
 
                //TcpClient TcpScan = new TcpClient();
				try
				{
                    Socket TcpScan = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 
                    TcpScan.BeginConnect(new IPEndPoint(ipAddress, i), EndConnect, TcpScan);
 
                    Interlocked.Increment(ref waitingForResponses);
 
                    //Logtxt.AppendText("Port numer: " + i + " jest OTWARTY\r\n");
				}
				catch
				{
                   // Logtxt.AppendText("Port numer:" + i + " jest zamknięty\r\n");
				}
				StatusSkanu.PerformStep();
			}
			Cursor.Current = Cursors.Arrow;
        }
        static void IncrementResponses()
        {
            Interlocked.Increment(ref waitingForResponses);
        }
 
        static void DecrementResponses()
        {
            Interlocked.Decrement(ref waitingForResponses);
        }
    }
 
} 
4

aby obliczenia odbywaly sie na osobnym watku mozesz uzyc klasy Task https://msdn.microsoft.com/en-us/library/system.threading.tasks.task%28v=vs.110%29.aspx
zeby zaktualizowac widok z 'wewnatrz' watku odpowiedzialnego za obliczenia powinienes uzyc np. Control.BeginInvoke https://msdn.microsoft.com/en-us/library/0b1bf3y3(v=vs.110).aspx

0

Dzięki za podpowiedź ale sam rozwiązałem problem : )

1 użytkowników online, w tym zalogowanych: 0, gości: 1