当我们要创建一个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();
}
}
}
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

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

  1. C#动态获取本机可用串口的两种方式

    1. private void GetSerialPort() //获取串口列表 { RegistryKey keyCom = Registry.LocalMachine.OpenSubKey(&qu ...

  2. C++ Socket 获取本机可用端口号(QT)

    :加载套接字库,创建套接字(WSAStartup()/socket()): :绑定套接字到一个IP地址和一个端口上(bind()): :将套接字设置为监听模式等待连接请求(listen()): :请求 ...

  3. C# — 动态获取本地IP地址及可用端口

    1.在VS中动态获取本地IP地址,代码如下: 2.获取本机的可用端口以及已使用的端口:

  4. 用C++和shell获取本机CPU、网卡IO、内存、磁盘等的基本信息

    用C++和shell获取本机CPU.网卡.内存.磁盘等的基本信息: 由于对C++相关的函数没多少了解,但是觉得用shell反而相对简单一些: 一.shell脚本,用来辅助C++获取主机的资源使用信息 ...

  5. C#获取本机磁盘信息

    照着书敲的.留作笔记吧. using System; using System.Collections.Generic; using System.Linq; using System.Text; u ...

  6. 获取本机IP、mac地址、计算机名

    python获取本机IP.mac地址.计算机名 在python中获取ip地址和在php中有很大不同,我们先来看一下python 获得本机MAC地址: >>> import uuid ...

  7. python获取本机IP、mac地址、计算机名

    在python中获取ip地址和在php中有很大不同,在php中往往比较简单.那再python中怎么做呢? 我们先来看一下python 获得本机MAC地址: 1 2 3 4 import uuid de ...

  8. 获取本机CPU,硬盘等使用情况

    早上的时候接到主管的一个任务,要获取服务器上的cpu,硬盘, 数据库等 的使用情况,并以邮件的方式发给boss, = =没办法,公司的服务器真是不敢恭维,顺便吐槽一下公司的网速,卡的时候30k左右徘徊 ...

  9. 如何获取本机IP

    GetLocalHost 直接通过InetAddress.getLocalHost()来获取,其主要逻辑如下 InetAddress.getLocalHost(): String hostname = ...

随机推荐

  1. opencv计算运行时间

    double Time = (double)cvGetTickCount();//  算法过程Time = (double)cvGetTickCount() - Time ; printf( &quo ...

  2. Java面试常见知识点总结(三)

    21.volatile关键字: 一旦一个共享变量(类的成员变量.类的静态成员变量)被volatile修饰之后,那么就具备了两层语义:   (1) 保证了不同线程对这个变量进行操作时的可见性,即一个线程 ...

  3. ***CodeIgniter集成微信支付(转)

    微信支付Native扫码支付模式二之CodeIgniter集成篇  http://www.cnblogs.com/24la/p/wxpay-native-qrcode-codeigniter.html ...

  4. Ext.js细节:在MVC中处理Widget Column,GetCmp和ComponentQuery, Id和ItemId

    针对EXT.JS版本的演进,要不断的学习新的最佳实践方法. 比如,在定义组件时,尽管用itemid,而不是id. 在搜索组件时,尽量用ComponentQuery,而不是getCmp. 在MVC中处理 ...

  5. 联想笔记本如何开启笔记本的VT-x虚拟化技术功能

    虚拟化技术支持,需几个方面的条件支持:芯片组自身支持.BIOS提供支持.处理器自身支持.操作系统支持. 操作系统方面,主流操作系统均支持VMM管理,因此无需考虑. 而芯片组方面,从Intel 945( ...

  6. winform快速开发平台 -> 通用权限管理之动态菜单

    这几个月一直忙APP的项目,没来得及更新项目,想想该抽出时间整理一下开发思路,跟大家分享,同时也希望得到宝贵的建议. 先说一下我们的权限管理的的设计思路,首先一个企业信息化管理系统一定会用到权限管理, ...

  7. CozyRSS开发记录12-MVVM,绑定RSS源和数据

    CozyRSS开发记录12-MVVM,绑定RSS源和数据 1.引入MvvmLight MVVM最近貌似在前端那块也挺火的.据说,WPF的程序如果不用MVVM,那跟MFC和winform的,也没啥区别. ...

  8. Andriod学习笔记5:通过NDK在C++中实现日志输出

    开发环境 android studio 1.5.1 实现步骤 新建android项目 项目名称为AndroidCLog,选择Empty Activity模板,其他默认即可. 下载配置ndk 在项目上右 ...

  9. 结合谷歌地图多边形(polygon)与Sql Server 2008的空间数据类型计算某个点是否在多边形内的注意事项

    首先在利用 GEOGRAPHY::STPolyFromText(@GeoStr, 4326) 这样的函数把字符串转换为Geography类型时,字符串里经纬度的顺序是 “经度[空格]纬度”,即“lon ...

  10. mysql 列类型