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”微信公众号

时间: 2024-07-28 16:09:44

C#获取本机可用端口的相关文章

串口api-QT串口编程,如何获取电脑当前可用端口名。

问题描述 QT串口编程,如何获取电脑当前可用端口名. 在QT串口编程中,我使用的是第三方类qextserialport,里面好像没有获取端口名的函数,我想把可用的端口名放在下拉框里,手动设置不合理啊.求指导. 解决方案 调用windows API,查询注册表获取当前可用的端口,已解决.

winphone 获取本机应用

问题描述 winphone 获取本机应用 winphone能获取到本机所安装的应用信息么?如果能获取,怎么获取?求大神帮忙!!! 解决方案 如果是您自己发布的应用,可用通过 API FindPackagesForCurrentPublisher 来获取一份应用安装列表. 但是,现在还暂时没有API或什么方法去检查别的开发者发布的应用. 解决方案二: 在应用层面没办法做到,因为每个应用工作在沙盒中.不过如果两个应用都是你开发的,或者那个应用提供了接口,你可以判断它是否存在. 这个相当于网络通讯.

java-Java 获取本机的外网ip

问题描述 Java 获取本机的外网ip Java 获取本机的外网ip. 本机为linux系统 快解救一下我吧 解决方案 import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; public class Listip { public static void main(String[] args) throws Exception { System.out.println(.....

获取本机通讯薄的内容

简介 如果你想获取本机通讯簿(Outlook Express和Outlook2000)的内容,如:联系人名字.联系人邮件地址等时,可以试试下面的方法.下面是把此方法用VC6编写的示例程序运行效果: 由于读取Outlook Express(系统自带)和Outlook2000(Office2000中所带)中通讯薄内容所采取的方法不同,下面将分开简述. 第一.读取系统自带Outlook Express中通讯薄方法 基本思路 通过载入Wab32.dll文件(此文件一般位于路径"<盘符>\Pr

C#获取本机的MAC地址\序列号\硬盘序列号

1 /// <summary> 2 /// 显示MAC地址 3 /// </summary> 4 /// <returns></returns> 5 private string GetMAC() 6 { 7 string mac = "本机的MAC地址:"; 8 using (ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration&

利用Java获取本机mac地址

public static void getAllMacAdress() { Enumeration<NetworkInterface> netInterfaces = null; try { // 获得所有网络接口 netInterfaces = NetworkInterface.getNetworkInterfaces(); while (netInterfaces.hasMoreElements()) { System.out .println("===============

.net获取本机公网IP地址示例

 本文主要介绍了.net获取本机公网IP地址的方法,使用了ip138的数据,大家参考使用吧 代码很简单,直接看代码   代码如下: using System; using System.Net; using System.Text.RegularExpressions;   namespace Keleyi.Com {     public class GetInternetIP     {         public static string GetIP()         {      

python简单获取本机计算机名和IP地址的方法

  本文实例讲述了python简单获取本机计算机名和IP地址的方法.分享给大家供大家参考.具体实现方法如下: 方法一: ? 1 2 3 4 5 6 7 8 9 10 >>> import socket >>> hostname = socket.gethostname() >>> print hostname china-43226208c >>>ip = socket.gethostbyname(hostname) >>

python获取本机mac地址和ip地址的方法

  这篇文章主要介绍了python获取本机mac地址和ip地址的方法,涉及Python获取系统相关信息的技巧,需要的朋友可以参考下 本文实例讲述了python获取本机mac地址和ip地址的方法.分享给大家供大家参考.具体如下: ? 1 2 3 4 5 6 7 8 9 10 import sys, socket def getipaddrs(hostname): result = socket.getaddrinfo(hostname,None,0,socket.SOCK_STREAM) retu