亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

C#?WinForm實現(xiàn)檢查目標IP端口是否可連接

 更新時間:2025年01月10日 09:40:37   作者:tpen  
這篇文章主要為大家詳細介紹了如何基于C#?WinForm實現(xiàn)檢查目標IP端口是否可連接的小工具,感興趣的小伙伴可以跟隨小編一起學習一下

一個小工具。

WinForm UI Code

namespace IPPort_CheckTool
{
    partial class MainForm
    {
        /// <summary>
        /// 必需的設(shè)計器變量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的資源。
        /// </summary>
        /// <param name="disposing">如果應(yīng)釋放托管資源,為 true;否則為 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗體設(shè)計器生成的代碼

        /// <summary>
        /// 設(shè)計器支持所需的方法 - 不要修改
        /// 使用代碼編輯器修改此方法的內(nèi)容。
        /// </summary>
        private void InitializeComponent()
        {
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.txt_Time = new System.Windows.Forms.Label();
            this.txt_CoreNum = new System.Windows.Forms.Label();
            this.txt_Active = new System.Windows.Forms.Label();
            this.txt_NoActive = new System.Windows.Forms.Label();
            this.btn_Start = new System.Windows.Forms.Button();
            this.label3 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label1 = new System.Windows.Forms.Label();
            this.txt_PortEnd = new System.Windows.Forms.TextBox();
            this.txt_PortStart = new System.Windows.Forms.TextBox();
            this.txt_IP = new System.Windows.Forms.TextBox();
            this.listBox_NoActive = new System.Windows.Forms.ListBox();
            this.listBox_ActivePort = new System.Windows.Forms.ListBox();
            this.progressBar = new System.Windows.Forms.ProgressBar();
            this.groupBox1.SuspendLayout();
            this.SuspendLayout();
            // 
            // groupBox1
            // 
            this.groupBox1.Controls.Add(this.progressBar);
            this.groupBox1.Controls.Add(this.txt_Time);
            this.groupBox1.Controls.Add(this.txt_CoreNum);
            this.groupBox1.Controls.Add(this.txt_Active);
            this.groupBox1.Controls.Add(this.txt_NoActive);
            this.groupBox1.Controls.Add(this.btn_Start);
            this.groupBox1.Controls.Add(this.label3);
            this.groupBox1.Controls.Add(this.label2);
            this.groupBox1.Controls.Add(this.label1);
            this.groupBox1.Controls.Add(this.txt_PortEnd);
            this.groupBox1.Controls.Add(this.txt_PortStart);
            this.groupBox1.Controls.Add(this.txt_IP);
            this.groupBox1.Dock = System.Windows.Forms.DockStyle.Top;
            this.groupBox1.Location = new System.Drawing.Point(3, 3);
            this.groupBox1.Margin = new System.Windows.Forms.Padding(5);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Padding = new System.Windows.Forms.Padding(5);
            this.groupBox1.Size = new System.Drawing.Size(1058, 127);
            this.groupBox1.TabIndex = 0;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "配置:";
            // 
            // txt_Time
            // 
            this.txt_Time.AutoSize = true;
            this.txt_Time.ForeColor = System.Drawing.Color.Green;
            this.txt_Time.Location = new System.Drawing.Point(844, 101);
            this.txt_Time.Name = "txt_Time";
            this.txt_Time.Size = new System.Drawing.Size(74, 21);
            this.txt_Time.TabIndex = 10;
            this.txt_Time.Text = "耗時:0s";
            // 
            // txt_CoreNum
            // 
            this.txt_CoreNum.AutoSize = true;
            this.txt_CoreNum.ForeColor = System.Drawing.Color.Green;
            this.txt_CoreNum.Location = new System.Drawing.Point(610, 101);
            this.txt_CoreNum.Name = "txt_CoreNum";
            this.txt_CoreNum.Size = new System.Drawing.Size(120, 21);
            this.txt_CoreNum.TabIndex = 9;
            this.txt_CoreNum.Text = "CPU核心總數(shù):0";
            // 
            // txt_Active
            // 
            this.txt_Active.AutoSize = true;
            this.txt_Active.ForeColor = System.Drawing.Color.Green;
            this.txt_Active.Location = new System.Drawing.Point(389, 101);
            this.txt_Active.Name = "txt_Active";
            this.txt_Active.Size = new System.Drawing.Size(119, 21);
            this.txt_Active.TabIndex = 8;
            this.txt_Active.Text = "激活端口總數(shù):0";
            // 
            // txt_NoActive
            // 
            this.txt_NoActive.AutoSize = true;
            this.txt_NoActive.Location = new System.Drawing.Point(3, 101);
            this.txt_NoActive.Name = "txt_NoActive";
            this.txt_NoActive.Size = new System.Drawing.Size(135, 21);
            this.txt_NoActive.TabIndex = 7;
            this.txt_NoActive.Text = "未激活端口總數(shù):0";
            // 
            // btn_Start
            // 
            this.btn_Start.Location = new System.Drawing.Point(915, 30);
            this.btn_Start.Name = "btn_Start";
            this.btn_Start.Size = new System.Drawing.Size(123, 56);
            this.btn_Start.TabIndex = 6;
            this.btn_Start.Text = "開始測試端口是否激活";
            this.btn_Start.UseVisualStyleBackColor = true;
            this.btn_Start.Click += new System.EventHandler(this.btn_Start_Click);
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(530, 41);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(78, 21);
            this.label3.TabIndex = 5;
            this.label3.Text = "結(jié)束端口:";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(252, 41);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(78, 21);
            this.label2.TabIndex = 4;
            this.label2.Text = "開始端口:";
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(23, 41);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(29, 21);
            this.label1.TabIndex = 3;
            this.label1.Text = "IP:";
            // 
            // txt_PortEnd
            // 
            this.txt_PortEnd.Location = new System.Drawing.Point(633, 41);
            this.txt_PortEnd.Name = "txt_PortEnd";
            this.txt_PortEnd.Size = new System.Drawing.Size(150, 29);
            this.txt_PortEnd.TabIndex = 2;
            // 
            // txt_PortStart
            // 
            this.txt_PortStart.Location = new System.Drawing.Point(355, 41);
            this.txt_PortStart.Name = "txt_PortStart";
            this.txt_PortStart.Size = new System.Drawing.Size(150, 29);
            this.txt_PortStart.TabIndex = 1;
            // 
            // txt_IP
            // 
            this.txt_IP.Location = new System.Drawing.Point(77, 41);
            this.txt_IP.Name = "txt_IP";
            this.txt_IP.Size = new System.Drawing.Size(150, 29);
            this.txt_IP.TabIndex = 0;
            // 
            // listBox_NoActive
            // 
            this.listBox_NoActive.Dock = System.Windows.Forms.DockStyle.Left;
            this.listBox_NoActive.ForeColor = System.Drawing.Color.Gray;
            this.listBox_NoActive.FormattingEnabled = true;
            this.listBox_NoActive.ItemHeight = 21;
            this.listBox_NoActive.Location = new System.Drawing.Point(3, 130);
            this.listBox_NoActive.Name = "listBox_NoActive";
            this.listBox_NoActive.Size = new System.Drawing.Size(383, 548);
            this.listBox_NoActive.TabIndex = 1;
            // 
            // listBox_ActivePort
            // 
            this.listBox_ActivePort.Dock = System.Windows.Forms.DockStyle.Fill;
            this.listBox_ActivePort.ForeColor = System.Drawing.Color.Green;
            this.listBox_ActivePort.FormattingEnabled = true;
            this.listBox_ActivePort.ItemHeight = 21;
            this.listBox_ActivePort.Location = new System.Drawing.Point(386, 130);
            this.listBox_ActivePort.Name = "listBox_ActivePort";
            this.listBox_ActivePort.Size = new System.Drawing.Size(675, 548);
            this.listBox_ActivePort.TabIndex = 2;
            // 
            // progressBar
            // 
            this.progressBar.Location = new System.Drawing.Point(798, 41);
            this.progressBar.Name = "progressBar";
            this.progressBar.Size = new System.Drawing.Size(100, 29);
            this.progressBar.TabIndex = 11;
            // 
            // MainForm
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 21F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(1064, 681);
            this.Controls.Add(this.listBox_ActivePort);
            this.Controls.Add(this.listBox_NoActive);
            this.Controls.Add(this.groupBox1);
            this.Font = new System.Drawing.Font("微軟雅黑", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.Margin = new System.Windows.Forms.Padding(5);
            this.Name = "MainForm";
            this.Padding = new System.Windows.Forms.Padding(3);
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "Hello!";
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox txt_PortEnd;
        private System.Windows.Forms.TextBox txt_PortStart;
        private System.Windows.Forms.TextBox txt_IP;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Button btn_Start;
        private System.Windows.Forms.ListBox listBox_NoActive;
        private System.Windows.Forms.ListBox listBox_ActivePort;
        private System.Windows.Forms.Label txt_NoActive;
        private System.Windows.Forms.Label txt_Active;
        private System.Windows.Forms.Label txt_CoreNum;
        private System.Windows.Forms.Label txt_Time;
        private System.Windows.Forms.ProgressBar progressBar;
    }
}

Main Code

using System;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace IPPort_CheckTool
{
    public partial class MainForm : Form
    {
        private Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
        private DateTime startTime;
        private Task[] tasks;

        private NotifyIcon notifyIcon;

        public MainForm()
        {
            InitializeComponent();

            var now = DateTime.Now;
            this.Text = $"Hello 今天是{now.ToString("dddd")}喲 ??";

            this.txt_IP.Text = ConfigurationManager.AppSettings["IP"].ToString();
            this.txt_PortStart.Text = ConfigurationManager.AppSettings["MinPortStart"].ToString();
            this.txt_PortEnd.Text = ConfigurationManager.AppSettings["MaxPortEnd"].ToString();
            this.txt_CoreNum.Text = $"CPU核心總數(shù):{Environment.ProcessorCount}";

            this.components = new System.ComponentModel.Container();
            this.notifyIcon = new NotifyIcon(this.components);
            this.notifyIcon.Visible = true;
            this.notifyIcon.MouseClick += (sn, en) => { if (en.Button == MouseButtons.Left) this.Show(); };
            var menus = new ContextMenu();
            var menu1= new MenuItem("退出軟件");
            menu1.Click += (s1, e1) => { this.Close(); };
            menus.MenuItems.Add(menu1);
            notifyIcon.ContextMenu= menus;
        }

        private void btn_Start_Click(object sender, EventArgs e)
        {
            string ip = this.txt_IP.Text.Trim();
            string min = this.txt_PortStart.Text.Trim();
            string max = this.txt_PortEnd.Text.Trim();

            if (string.IsNullOrWhiteSpace(ip) || string.IsNullOrWhiteSpace(min) || string.IsNullOrWhiteSpace(max))
            {
                MessageBox.Show("不能為空!");
                return;
            }

            if (!int.TryParse(min, out var minPort) || !int.TryParse(max, out var maxPort))
            {
                MessageBox.Show("端口不是整數(shù)!");
                return;
            }

            config.AppSettings.Settings["IP"].Value = ip;
            config.AppSettings.Settings["MinPortStart"].Value = min;
            config.AppSettings.Settings["MaxPortEnd"].Value = max;
            config.Save();
            ConfigurationManager.RefreshSection("appSettings");

            IPAddress targetIpAddress = IPAddress.Parse(ip);
            var ipadrlist = Dns.GetHostAddresses(Dns.GetHostName()).ToList();
            ipadrlist.Add(IPAddress.Parse("127.0.0.1"));
            ipadrlist.Add(IPAddress.Parse("0.0.0.0"));
            if (ipadrlist.Contains(targetIpAddress))
            {
                CheckLocalPort(minPort, maxPort);//本地IP
            }
            else
            {
                CheckRemotePort(ip, minPort, maxPort);//遠程IP
            }
        }

        private void CheckLocalPort(int minPort, int maxPort)
        {
            btn_Start.Enabled = false;

            listBox_NoActive.Items.Clear();
            listBox_ActivePort.Items.Clear();
            startTime = DateTime.Now;
            int length = maxPort - minPort + 1;
            progressBar.Maximum = length;
            progressBar.Minimum = 0;

            var ips = IPGlobalProperties.GetIPGlobalProperties();
            var activeIps = ips.GetActiveTcpListeners().Select(p => p.Port).ToHashSet();

            Task.Factory.StartNew(new Action(() =>
            {
                for (int i = minPort; i <= maxPort; i++)
                {
                    int port = i;
                    this?.Invoke(new Action(() =>
                    {
                        if (activeIps.Contains(port))
                        {
                            listBox_ActivePort.Items.Insert(0, port);
                            txt_Active.Text = $"激活端口總數(shù):{listBox_ActivePort.Items.Count}";
                        }
                        else
                        {
                            listBox_NoActive.Items.Insert(0, port);
                            txt_NoActive.Text = $"未激活端口總數(shù):{listBox_NoActive.Items.Count}";
                        }
                        progressBar.Value = listBox_ActivePort.Items.Count + listBox_NoActive.Items.Count;
                        txt_Time.Text = $"耗時:{(DateTime.Now - startTime).TotalSeconds.ToString()}s";

                        //耗時操作卡死UI 處理方法
                        Application.DoEvents();
                    }));
                }

            })).ContinueWith(p => InitUI());

        }

        private void CheckRemotePort(string ip, int minPort, int maxPort)
        {
            btn_Start.Enabled = false;

            listBox_NoActive.Items.Clear();
            listBox_ActivePort.Items.Clear();
            startTime = DateTime.Now;
            int length = maxPort - minPort + 1;
            tasks = new Task[length];
            progressBar.Maximum = length;
            progressBar.Minimum = 0;

            Task.Run(() =>
            {
                for (int i = minPort; i <= maxPort; i++)
                {
                    int port = i;
                    var task = Task.Factory.StartNew(new Action(() =>
                    {
                        var res = CheckRemotePortCanConnect(ip, port);
                        this?.Invoke(new Action(() =>
                        {
                            if (res.Item1)
                            {
                                listBox_ActivePort.Items.Insert(0, res.Item2);
                                txt_Active.Text = $"激活端口總數(shù):{listBox_ActivePort.Items.Count}";
                            }
                            else
                            {
                                listBox_NoActive.Items.Insert(0, res.Item2);
                                txt_NoActive.Text = $"未激活端口總數(shù):{listBox_NoActive.Items.Count}";
                            }
                            progressBar.Value = listBox_ActivePort.Items.Count + listBox_NoActive.Items.Count;
                            txt_Time.Text = $"耗時:{(DateTime.Now - startTime).TotalSeconds.ToString()}s";

                            //耗時操作卡死UI 處理方法
                            Application.DoEvents();
                        }));
                    }));
                    tasks[i - minPort] = task;
                }

                Task.WaitAll(tasks);

            }).ContinueWith(p => InitUI());
        }

        private void InitUI()
        {
            this?.Invoke(new Action(() => { btn_Start.Enabled = true; }));
        }

        private (bool,int) CheckRemotePortCanConnect(string ipString, int port)
        {
            IPAddress ip = IPAddress.Parse(ipString);

            bool isConnect = false;

            TcpClient tcp = new TcpClient();
            try
            {
                tcp.Connect(ip, port);
                isConnect = tcp.Connected;
            }
            catch (Exception)
            {
                isConnect = false;
            }
            finally
            {
                tcp?.Close();
                tcp?.Dispose();
            }
            return (isConnect, port);
        }
    }
}

引用:

C#檢查服務(wù)器ip和端口是否通暢,是否可訪問

 		/// <summary>
        /// 檢查服務(wù)器和端口是否可以連接
        /// </summary>
        /// <param name="ipString">服務(wù)器ip</param>
        /// <param name="port">端口</param>
        /// <returns></returns>
        public static bool CheckConnect(string ipString, int port)
        {
            bool right =false;
            System.Net.Sockets.TcpClient tcpClient = new System.Net.Sockets.TcpClient()
            { SendTimeout = 1000 };
            IPAddress ip = IPAddress.Parse(ipString);
            try
            {              
			    var result = tcpClient.BeginConnect(ip, port, null, null);
			    var back = result.AsyncWaitHandle.WaitOne(2000);
			    right = tcpClient.Connected;
            }
            catch (Exception ex)
            {
                //LogHelpter.AddLog($"連接服務(wù){(diào)ipString}:{port}失敗,設(shè)置的超時時間{tcpClient.SendTimeout}毫秒");
                //連接失敗
                return false;
            }           
            tcpClient.Close();
            tcpClient.Dispose();
            return right;
        }

以上就是C# WinForm實現(xiàn)檢查目標IP端口是否可連接的詳細內(nèi)容,更多關(guān)于C#檢查目標IP端口是否可連接的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • C# 標準事件流實例代碼

    C# 標準事件流實例代碼

    這篇文章主要介紹了C# 標準事件流的實例代碼,文中講解非常細致,代碼幫助大家更好的理解和學習,感興趣的朋友可以了解下
    2020-07-07
  • c#程序刪除自身代碼示例分享

    c#程序刪除自身代碼示例分享

    偶然看到一個可以自刪除的程序,于是了解下如何實現(xiàn)。然后整理如下,需要的朋友可以參考下
    2014-03-03
  • 使用C#實現(xiàn)一個簡單的繪圖工具

    使用C#實現(xiàn)一個簡單的繪圖工具

    這篇文章主要為大家詳細介紹了如何使用C#開發(fā)的簡單繪圖工具,可以將簽名簡單繪圖后的效果以圖片的形式導出,有需要的小伙伴可以跟隨小編一起學習一下
    2024-02-02
  • 分析C# Dictionary的實現(xiàn)原理

    分析C# Dictionary的實現(xiàn)原理

    對于C#中的Dictionary類相信大家都不陌生,這是一個Collection(集合)類型,可以通過Key/Value(鍵值對的形式來存放數(shù)據(jù);該類最大的優(yōu)點就是它查找元素的時間復雜度接近O(1)。那么什么樣的設(shè)計能使得Dictionary類實現(xiàn)O(1)的時間復雜度呢
    2021-06-06
  • C#中的文件路徑獲取函數(shù)和文件名字獲取函數(shù)小結(jié)

    C#中的文件路徑獲取函數(shù)和文件名字獲取函數(shù)小結(jié)

    這篇文章主要介紹了C#中的文件路徑獲取函數(shù)和文件名字獲取函數(shù)小結(jié),本文講解了獲取絕對文件路徑、獲取文件名字、獲得包含 path 目錄信等內(nèi)容,需要的朋友可以參考下
    2015-01-01
  • c# 獲取數(shù)據(jù)庫中所有表名稱的方法

    c# 獲取數(shù)據(jù)庫中所有表名稱的方法

    在很多情況下我們需要將指定的數(shù)據(jù)庫中的所有表都列出來。在使用c#進行軟件開發(fā)時,我們有哪些方法可是實現(xiàn)這個目的呢?本人對此進行概要的總結(jié),有以下6中方式可以實現(xiàn)這個目的。
    2010-02-02
  • 基于C#實現(xiàn)的仿windows左側(cè)伸縮菜單效果

    基于C#實現(xiàn)的仿windows左側(cè)伸縮菜單效果

    這篇文章主要介紹了基于C#實現(xiàn)的仿windows左側(cè)伸縮菜單效果,比較實用的功能,需要的朋友可以參考下
    2014-08-08
  • C#直線的最小二乘法線性回歸運算實例

    C#直線的最小二乘法線性回歸運算實例

    這篇文章主要介紹了C#直線的最小二乘法線性回歸運算方法,實例分析了給定一組點,用最小二乘法進行線性回歸運算的實現(xiàn)技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-08-08
  • C#開發(fā)WPF程序中的弱事件模式

    C#開發(fā)WPF程序中的弱事件模式

    這篇文章介紹了C#開發(fā)WPF程序中的弱事件模式,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-06-06
  • Unity擴展Hierachry的右鍵菜單

    Unity擴展Hierachry的右鍵菜單

    這篇文章主要為大家詳細介紹了Unity擴展Hierachry的右鍵菜單,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-02-02

最新評論