C#获取本机可用端口
生活随笔
收集整理的這篇文章主要介紹了
C#获取本机可用端口
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
當我們要創建一個Tcp/UDP Server connection ,我們需要一個范圍在1000到65535之間的端口 。但是本機一個端口只能一個程序監聽,所以我們進行本地監聽的時候需要檢測端口是否被占用。命名空間System.Net.NetworkInformation下定義了一個名為IPGlobalProperties的類,我們使用這個類可以獲取所有的監聽連接,然后判斷端口是否被占用.
//----------------------------------------------------------------------------- // Filename: FreePort.cs // // Description: Helper methods to find the next free UDP and TCP ports. // // History: // 28 Mar 2012 Aaron Clauson Copied from http://www.mattbrindley.com/developing/windows/net/detecting-the-next-available-free-tcp-port/. //-----------------------------------------------------------------------------using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Text; using System.Threading;namespace SIPSorcery.Sys.Net { public class FreePort { private const string PortReleaseGuid = "8875BD8E-4D5B-11DE-B2F4-691756D89593";/// <summary> /// Check if startPort is available, incrementing and /// checking again if it's in use until a free port is found /// </summary> /// <param name="startPort">The first port to check</param> /// <returns>The first available port</returns> public static int FindNextAvailableTCPPort(int startPort) { int port = startPort; bool isAvailable = true;var mutex = new Mutex(false, string.Concat("Global/", PortReleaseGuid)); mutex.WaitOne(); try { IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); IPEndPoint[] endPoints = ipGlobalProperties.GetActiveTcpListeners();do { if (!isAvailable) { port++; isAvailable = true; }foreach (IPEndPoint endPoint in endPoints) { if (endPoint.Port != port) continue; isAvailable = false; break; }} while (!isAvailable && port < IPEndPoint.MaxPort);if (!isAvailable) throw new ApplicationException("Not able to find a free TCP port.");return port; } finally { mutex.ReleaseMutex(); } }/// <summary> /// Check if startPort is available, incrementing and /// checking again if it's in use until a free port is found /// </summary> /// <param name="startPort">The first port to check</param> /// <returns>The first available port</returns> public static int FindNextAvailableUDPPort(int startPort) { int port = startPort; bool isAvailable = true;var mutex = new Mutex(false, string.Concat("Global/", PortReleaseGuid)); mutex.WaitOne(); try { IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); IPEndPoint[] endPoints = ipGlobalProperties.GetActiveUdpListeners();do { if (!isAvailable) { port++; isAvailable = true; }foreach (IPEndPoint endPoint in endPoints) { if (endPoint.Port != port) continue; isAvailable = false; break; }} while (!isAvailable && port < IPEndPoint.MaxPort);if (!isAvailable) throw new ApplicationException("Not able to find a free TCP port.");return port; } finally { mutex.ReleaseMutex(); } } } }總結
以上是生活随笔為你收集整理的C#获取本机可用端口的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 中国银行排名,中国各大银行排名一览
- 下一篇: c# char unsigned_dll