[轉] C# 擷取本機可用連接埠

來源:互聯網
上載者:User

標籤:des   style   blog   http   io   color   ar   使用   sp   

當我們要建立一個Tcp/UDP Server connection ,我們需要一個範圍在1000到65535之間的連接埠 。但是本機一個連接埠只能一個程式監聽,所以我們進行本地監聽的時候需要檢測連接埠是否被佔用。命名空間System.Net.NetworkInformation下定義了一個名為IPGlobalProperties的類,我們使用這個類可以擷取所有的監聽串連,然後判斷連接埠是否被佔用。

  1 //-----------------------------------------------------------------------------   2 // Filename: FreePort.cs   3 //   4 // Description: Helper methods to find the next free UDP and TCP ports.   5 //   6 // History:   7 // 28 Mar 2012    Aaron Clauson    Copied from http://www.mattbrindley.com/developing/windows/net/detecting-the-next-available-free-tcp-port/.   8 //-----------------------------------------------------------------------------  9  10 using System;  11 using System.Collections.Generic;  12 using System.Linq;  13 using System.Net;  14 using System.Net.NetworkInformation;  15 using System.Text;  16 using System.Threading; 17  18 namespace SIPSorcery.Sys.Net  19 {  20     public class FreePort  21     {  22         private const string PortReleaseGuid = "8875BD8E-4D5B-11DE-B2F4-691756D89593"; 23  24         /// <summary>  25         /// Check if startPort is available, incrementing and  26         /// checking again if it‘s in use until a free port is found  27         /// </summary>  28         /// <param name="startPort">The first port to check</param>  29         /// <returns>The first available port</returns>  30         public static int FindNextAvailableTCPPort(int startPort)  31         {  32             int port = startPort;  33             bool isAvailable = true; 34  35             var mutex = new Mutex(false,  36                 string.Concat("Global/", PortReleaseGuid));  37             mutex.WaitOne();  38             try  39             {  40                 IPGlobalProperties ipGlobalProperties =  41                     IPGlobalProperties.GetIPGlobalProperties();  42                 IPEndPoint[] endPoints =  43                     ipGlobalProperties.GetActiveTcpListeners(); 44  45                 do  46                 {  47                     if (!isAvailable)  48                     {  49                         port++;  50                         isAvailable = true;  51                     } 52  53                     foreach (IPEndPoint endPoint in endPoints)  54                     {  55                         if (endPoint.Port != port) continue;  56                         isAvailable = false;  57                         break;  58                     } 59  60                 } while (!isAvailable && port < IPEndPoint.MaxPort); 61  62                 if (!isAvailable)  63                     throw new ApplicationException("Not able to find a free TCP port."); 64  65                 return port;  66             }  67             finally  68             {  69                 mutex.ReleaseMutex();  70             }  71         } 72  73         /// <summary>  74         /// Check if startPort is available, incrementing and  75         /// checking again if it‘s in use until a free port is found  76         /// </summary>  77         /// <param name="startPort">The first port to check</param>  78         /// <returns>The first available port</returns>  79         public static int FindNextAvailableUDPPort(int startPort)  80         {  81             int port = startPort;  82             bool isAvailable = true; 83  84             var mutex = new Mutex(false,  85                 string.Concat("Global/", PortReleaseGuid));  86             mutex.WaitOne();  87             try  88             {  89                 IPGlobalProperties ipGlobalProperties =  90                     IPGlobalProperties.GetIPGlobalProperties();  91                 IPEndPoint[] endPoints =  92                     ipGlobalProperties.GetActiveUdpListeners(); 93  94                 do  95                 {  96                     if (!isAvailable)  97                     {  98                         port++;  99                         isAvailable = true; 100                     }101 102                     foreach (IPEndPoint endPoint in endPoints) 103                     { 104                         if (endPoint.Port != port) 105                             continue; 106                         isAvailable = false; 107                         break; 108                     }109 110                 } while (!isAvailable && port < IPEndPoint.MaxPort);111 112                 if (!isAvailable) 113                     throw new ApplicationException("Not able to find a free TCP port.");114 115                 return port; 116             } 117             finally 118             { 119                 mutex.ReleaseMutex(); 120             } 121         } 122     } 123 } 

 

[轉] C# 擷取本機可用連接埠

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.