zoukankan      html  css  js  c++  java
  • 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(); 
                } 
            } 
        } 
    } 
  • 相关阅读:
    [ARC074C] RGB Sequence
    [SHOI2014] 概率充电器
    CF368B Sereja and Suffixes
    CF980D Perfect Groups
    Rainbow Roads(gym101617G)(DFS序,差分)
    Educational Codeforces Round 104 (Rated for Div. 2)(A~E)
    Floor and Mod(CF1485C)(数论)
    Longest Simple Cycle(CF1476C)(线性dp)
    Factories(Gym102222G)(树形dp+背包)
    Codeforces Round #699 (Div. 2)(A,B,C,D)
  • 原文地址:https://www.cnblogs.com/shanyou/p/3535246.html
Copyright © 2011-2022 走看看