c# socket 判斷端口是否被占用


最近在搞 socket ,遇到端口占用的問題,程序需要自動檢測端口是否占用,提醒服務端的端口更改。

於是,baidu下,發現居然都是,用try——catch  異常去判斷是否占用,很是傷心啊。

現貼出下面代碼,獲取系統在已經使用的端口進行判斷。

internal static bool PortInUse(int port)
        {
            bool inUse = false;

            IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
            IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();


            foreach (IPEndPoint endPoint in ipEndPoints)
            {
                if (endPoint.Port == port)
                {
                    inUse = true;
                    break;
                }
            }


            return inUse;
        }



免責聲明!

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



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