c#判斷指定端口號是否被占用


本文系原創

分享判斷指定端口號是否被占用的兩種方法:

        /// <summary>
        /// 判斷指定端口號是否被占用
        /// </summary>
        /// <param name="port"></param>
        /// <returns></returns>
        internal static Boolean IsPortOccupedFun1(Int32 port)
        {
            Boolean result = false;
            try
            {
                Process p = new Process();
                p.StartInfo = new ProcessStartInfo("netstat", "-an");
                p.StartInfo.CreateNoWindow = true;
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                p.StartInfo.RedirectStandardOutput = true;
                p.Start();
                String output = p.StandardOutput.ReadToEnd().ToLower();
                string ip1 = "127.0.0.1";
                string ip2 = "0.0.0.0";
                System.Net.IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;
                List<string> ipList = new List<string>();
                ipList.Add(ip1);
                ipList.Add(ip2);
                for (int i = 0; i < addressList.Length; i++)
                {
                    ipList.Add(addressList[i].ToString());
                }

                
                for (int i = 0; i < ipList.Count; i++)
                {
                    if (output.IndexOf("tcp " + ipList[i] + ":" + port.ToString()) >= 0)
                    {
                        result = true;
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Application.ActiveApplication.Output.Output(ex);
            }
            return result;
        }    
        /// <summary>
        /// 判斷指定端口號是否被占用
        /// </summary>
        /// <param name="port"></param>
        /// <returns></returns>
        internal static Boolean IsPortOccupedFun2(Int32 port)
        {
            Boolean result = false;
            try
            {
                System.Net.NetworkInformation.IPGlobalProperties iproperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
                System.Net.IPEndPoint[] ipEndPoints = iproperties.GetActiveTcpListeners();
                foreach (var item in ipEndPoints)
                {
                    if (item.Port == port)
                    {
                        result = true;
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Application.ActiveApplication.Output.Output(ex);
            }
            return result;
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM