C# WinForm 端口扫描器
1.C# 控件转截图
2.C# WinForm 端口扫描器
- 一个小工具。测试样例
- 代码

using System; using System.Windows.Forms; namespace IPPort_CheckTool { internal static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } } }

using System; using System.Configuration; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Text; 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")}哟 🤭"; string ipOrDns = ConfigurationManager.AppSettings["IPOrDNS"].ToString(); this.txt_IPOrDNS.Items.Add(ipOrDns); this.txt_IPOrDNS.SelectedIndex = 0; this.txt_PortStart.Text = ConfigurationManager.AppSettings["MinPortStart"].ToString(); this.txt_PortEnd.Text = ConfigurationManager.AppSettings["MaxPortEnd"].ToString(); this.txt_CoreNum.Text = $"CPU核心总数:{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; //20250123 新增局域网IP下拉选项 _ = Task.Run(() => { //获取本机IP string _myHostIP = Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault<IPAddress>(a => a.AddressFamily.ToString().Equals("InterNetwork")).ToString(); //截取IP网段 string ipDuan = _myHostIP.Remove(_myHostIP.LastIndexOf('.')); //枚举网段计算机 Ping myPing = new Ping(); byte[] buffer = Encoding.ASCII.GetBytes(string.Empty); for (int i = 1; i <= 255; i++) { string pingIP = ipDuan + "." + i.ToString(); PingReply pingReply = myPing.Send(pingIP, 1000, buffer); if (pingReply.Status == IPStatus.Success) { this.txt_IPOrDNS?.Invoke(new Action(() => { this.txt_IPOrDNS.Items.Add(pingIP); this.groupBox1.Text = (i != 255) ? $"配置:{pingIP} ping OK" : "配置:"; })); } else { this.txt_IPOrDNS?.Invoke(new Action(() => { this.groupBox1.Text = (i != 255) ? $"配置:{pingIP} ping Fail" : "配置:"; })); } } }); //20250124 新增右键-全选、复制 this.listBox_ActivePort.SelectionMode = this.listBox_NoActive.SelectionMode = SelectionMode.MultiExtended; this.MenuActive_SelectAll.Click += ContentMenu_Click; this.MenuActive_Copy.Click += ContentMenu_Click; this.MenuNoActive_SelectAll.Click += ContentMenu_Click; this.MenuNoActive_Copy.Click += ContentMenu_Click; } private void ContentMenu_Click(object sender, EventArgs e) { var menu = sender as ToolStripMenuItem; switch (menu.Name) { case nameof(MenuActive_SelectAll): for (int i = listBox_ActivePort.Items.Count - 1; i >= 0; i--) { this.listBox_ActivePort.SetSelected(i, true); } break; case nameof(MenuActive_Copy): Clipboard.SetDataObject(string.Join("\r\n", listBox_ActivePort.SelectedItems.Cast<string>())); break; case nameof(MenuNoActive_SelectAll): for (int i = listBox_NoActive.Items.Count - 1; i >= 0; i--) { this.listBox_NoActive.SetSelected(i, true); } break; case nameof(MenuNoActive_Copy): Clipboard.SetDataObject(string.Join("\r\n", listBox_NoActive.SelectedItems.Cast<string>())); break; default: break; } } private void btn_Start_Click(object sender, EventArgs e) { string ipOrDns = this.txt_IPOrDNS.Text.Trim(); string min = this.txt_PortStart.Text.Trim(); string max = this.txt_PortEnd.Text.Trim(); if (string.IsNullOrWhiteSpace(ipOrDns) || string.IsNullOrWhiteSpace(min) || string.IsNullOrWhiteSpace(max)) { MessageBox.Show("不能为空!"); return; } if (!int.TryParse(min, out var minPort) || !int.TryParse(max, out var maxPort)) { MessageBox.Show("端口不是整数!"); return; } config.AppSettings.Settings["IPOrDNS"].Value = ipOrDns; config.AppSettings.Settings["MinPortStart"].Value = min; config.AppSettings.Settings["MaxPortEnd"].Value = max; config.Save(); ConfigurationManager.RefreshSection("appSettings"); //20250124 新增域名解析成IP if (!IPAddress.TryParse(ipOrDns, out var targetIpAddress)) { try { targetIpAddress = Dns.GetHostEntry(ipOrDns).AddressList[0]; } catch (Exception ex) { MessageBox.Show($"域名错误:{ex.Message}"); return; } } 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(targetIpAddress.ToString(), 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.ToString()); txt_Active.Text = $"激活端口总数:{listBox_ActivePort.Items.Count}"; } else { listBox_NoActive.Items.Insert(0, port.ToString()); txt_NoActive.Text = $"未激活端口总数:{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 = $"激活端口总数:{listBox_ActivePort.Items.Count}"; } else { listBox_NoActive.Items.Insert(0, res.Item2); txt_NoActive.Text = $"未激活端口总数:{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,string) 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.ToString()); } } }

namespace IPPort_CheckTool { partial class MainForm { /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的资源。 /// </summary> /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows 窗体设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要修改 /// 使用代码编辑器修改此方法的内容。 /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.txt_IPOrDNS = new System.Windows.Forms.ComboBox(); this.progressBar = new System.Windows.Forms.ProgressBar(); 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.listBox_NoActive = new System.Windows.Forms.ListBox(); this.contextMenu_NoActive = new System.Windows.Forms.ContextMenuStrip(this.components); this.MenuNoActive_SelectAll = new System.Windows.Forms.ToolStripMenuItem(); this.MenuNoActive_Copy = new System.Windows.Forms.ToolStripMenuItem(); this.listBox_ActivePort = new System.Windows.Forms.ListBox(); this.contextMenu_ActivePort = new System.Windows.Forms.ContextMenuStrip(this.components); this.MenuActive_SelectAll = new System.Windows.Forms.ToolStripMenuItem(); this.MenuActive_Copy = new System.Windows.Forms.ToolStripMenuItem(); this.groupBox1.SuspendLayout(); this.contextMenu_NoActive.SuspendLayout(); this.contextMenu_ActivePort.SuspendLayout(); this.SuspendLayout(); // // groupBox1 // this.groupBox1.Controls.Add(this.txt_IPOrDNS); 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.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_IPOrDNS // this.txt_IPOrDNS.FormattingEnabled = true; this.txt_IPOrDNS.Location = new System.Drawing.Point(77, 41); this.txt_IPOrDNS.Name = "txt_IPOrDNS"; this.txt_IPOrDNS.Size = new System.Drawing.Size(150, 29); this.txt_IPOrDNS.TabIndex = 12; // // 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; // // 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核心总数: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 = "激活端口总数: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 = "未激活端口总数: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(549, 44); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(78, 21); this.label3.TabIndex = 5; this.label3.Text = "结束端口:"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(271, 44); 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(3, 44); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(68, 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; // // listBox_NoActive // this.listBox_NoActive.ContextMenuStrip = this.contextMenu_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; // // contextMenu_NoActive // this.contextMenu_NoActive.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.MenuNoActive_SelectAll, this.MenuNoActive_Copy}); this.contextMenu_NoActive.Name = "contextMenu_NoActive"; this.contextMenu_NoActive.Size = new System.Drawing.Size(101, 48); // // MenuNoActive_SelectAll // this.MenuNoActive_SelectAll.Name = "MenuNoActive_SelectAll"; this.MenuNoActive_SelectAll.Size = new System.Drawing.Size(100, 22); this.MenuNoActive_SelectAll.Text = "全选"; // // MenuNoActive_Copy // this.MenuNoActive_Copy.Name = "MenuNoActive_Copy"; this.MenuNoActive_Copy.Size = new System.Drawing.Size(100, 22); this.MenuNoActive_Copy.Text = "复制"; // // listBox_ActivePort // this.listBox_ActivePort.ContextMenuStrip = this.contextMenu_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; // // contextMenu_ActivePort // this.contextMenu_ActivePort.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.MenuActive_SelectAll, this.MenuActive_Copy}); this.contextMenu_ActivePort.Name = "contextMenu_ActivePort"; this.contextMenu_ActivePort.Size = new System.Drawing.Size(101, 48); // // MenuActive_SelectAll // this.MenuActive_SelectAll.Name = "MenuActive_SelectAll"; this.MenuActive_SelectAll.Size = new System.Drawing.Size(100, 22); this.MenuActive_SelectAll.Text = "全选"; // // MenuActive_Copy // this.MenuActive_Copy.Name = "MenuActive_Copy"; this.MenuActive_Copy.Size = new System.Drawing.Size(100, 22); this.MenuActive_Copy.Text = "复制"; // // 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.KeyPreview = true; 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.contextMenu_NoActive.ResumeLayout(false); this.contextMenu_ActivePort.ResumeLayout(false); 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.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; private System.Windows.Forms.ComboBox txt_IPOrDNS; private System.Windows.Forms.ContextMenuStrip contextMenu_NoActive; private System.Windows.Forms.ContextMenuStrip contextMenu_ActivePort; private System.Windows.Forms.ToolStripMenuItem MenuNoActive_SelectAll; private System.Windows.Forms.ToolStripMenuItem MenuNoActive_Copy; private System.Windows.Forms.ToolStripMenuItem MenuActive_SelectAll; private System.Windows.Forms.ToolStripMenuItem MenuActive_Copy; } }

<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" /> </startup> <appSettings> <add key="IPOrDNS" value="127.0.0.1"/> <add key="MinPortStart" value="0"/> <add key="MaxPortEnd" value="65535"/> </appSettings> </configuration>
-
引用
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)