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(); 
                } 
            } 
        } 
    } 
  • 相关阅读:
    java ---------- API
    java ------- 泛型
    mybatis(输入、输出参数、ResultMap)
    javase参数传递机制(值传递)
    mybatis配置文件(properties、typeAliases、mappers( resource、class、url、package))
    mybatis(Mybatis与hibernate的不同、原始Dao开发、Mapper动态代理开发)
    mybatis入门(介绍、mybatis入门程序(增、删、改、查))
    javase(四舍五入、switch、length、构造器、重载与重写)
    javase(内存中的堆(heap)、栈(stack)和静态存储区)
    Javase(&与&&的区别和联系)
  • 原文地址:https://www.cnblogs.com/shanyou/p/3535246.html
Copyright © 2011-2022 走看看