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(); 
            } 
        } 
    } 
}

本文来自云栖社区合作伙伴“doNET跨平台”,了解相关信息可以关注“opendotnet”微信公众号

目录
相关文章
|
弹性计算 Shell Linux
|
9月前
|
SQL Apache Windows
Windows服务器80端口被占用的全面解决方案
在服务管理器中启动apache2服务,即可正常使用80端口。若系统中还安装了其他微软产品如sql等,也可尝试停止其服务进行测试,但请注意,SQL通常不会使用80端口,因此一般不会受到影响。以上就是关于80端口被system占用的详细解决方法,希望对你有所帮助。
|
7月前
|
网络协议
端口最多只有65535个,为什么服务器能承受百万并发
服务器通过四元组(源IP、源端口、目标IP、目标端口)识别不同TCP连接,每条连接对应独立socket。数据包携带四元组信息,服务端据此查找对应socket进行通信。只要四元组任一元素不同,即视为新连接,可创建独立socket。资源充足时,单进程可支持百万级并发连接,socket与端口非一一对应。
505 10
端口最多只有65535个,为什么服务器能承受百万并发
|
网络协议 安全 应用服务中间件
云服务器怎么开启被关闭的端口?手把手教你开启端口
在使用云服务器时,若发现某些服务无法访问,可能是端口被关闭。本文介绍了端口关闭的原因、检查方法及开启步骤。原因包括初始设置限制、防火墙规则和外部网络策略;可通过netstat或ss命令检查端口状态,用ufw、iptables或firewalld调整防火墙规则。最后提供了解决常见问题的建议,确保端口正常开放并可供外网访问。
2196 9
|
9月前
|
弹性计算 网络协议 安全
【转】如何配置服务器的端口映射?
本文详解端口映射原理及配置方法,涵盖家庭、企业与云环境,包含静态、动态与双向映射类型,并提供常见问题解决方案。
2082 6
|
弹性计算 应用服务中间件 Linux
阿里云服务器开放端口完整图文教程
笔者近期开发完成的服务端程序部署在阿里云的ECS云服务器上面,一些应用程序配置文件需要设置监听的端口(如Tomcat的8080、443端口等),虽然通过CentOs 7系统的的「防火墙」开放了对应的端口号,任然无法访问端口号对应的应用程序,后面了解到原来还需要设置云服务器的「安全组规则」,开放相应的端口权限,服务端的接口才能真正开放。
4600 1
阿里云服务器开放端口完整图文教程
|
SQL 关系型数据库 MySQL
云服务器常用端口作用
了解云服务器常用端口的作用有助于高效管理资源、快速定位问题及更好地使用云服务。常见端口包括:21(FTP,文件传输)、22(SSH,远程连接Linux)、25(SMTP,发送邮件)、80(HTTP,网页服务)、110/143(POP3/IMAP,接收邮件)、443(HTTPS,加密网页)、1433(SQL Server)、3306(MySQL)、3389(RDP,远程访问Windows桌面)和8080(代理服务)。
717 2
|
存储 安全 网络安全
阿里云国际站:阿里云服务器端口配置
悟空云@CloudWuKong阿里云是全球领先的云计算服务提供商,为用户提供弹性计算、数据库、存储、网络安全等一系列云计算服务。在使用阿里云服务器时,合理配置端口非常重要,可以提高服务器安全性和稳定性。
|
弹性计算 运维 数据安全/隐私保护
云服务器 ECS产品使用问题之如何更改服务器的IP地址或端口号
云服务器ECS(Elastic Compute Service)是各大云服务商阿里云提供的一种基础云计算服务,它允许用户租用云端计算资源来部署和运行各种应用程序。以下是一个关于如何使用ECS产品的综合指南。
下一篇
开通oss服务