当我们要创建一个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. MongoDB聚合运算之mapReduce函数的使用(11)

    mapReduce 随着"大数据"概念而流行. 其实mapReduce的概念非常简单, 从功能上说,相当于RDBMS的 group 操作 mapReduce的真正强项在哪? 答:在 ...

  2. Android studio 自定义打包apk名

    Android Studio打包应用默认生成的apk名称是:app-release.apk .如果我们要让生成的apk名跟我们版本包名有联系的话,那我们就要自定义生成的apk名了 需要在build.g ...

  3. C++ 系列:多线程资源收集

    Copyright © 1900-2016, NORYES, All Rights Reserved. http://www.cnblogs.com/noryes/ 欢迎转载,请保留此版权声明. -- ...

  4. oracle is not in the sudoers file. This incident will be reported.

    准备把OS的root禁用了,所以其他用户要执行使用root执行的操作时,需要使用sudo. 在没有配置sudo的时候,执行sudo会出现类似以下的报错: [oracle@test ~]$ sudo / ...

  5. Redis 数据库入门指南

    Redis 是一个开源数据库,它使用内存数据结构存储,可作为数据库.缓存和消息代理使用.Redis 支持丰富的数据结构,有:字符串(Strings).哈希(Hashs).列表(Lists).集合(Se ...

  6. SQL Server 得到数据库中所有表的名称及数据条数

    --方法一if exists ( select * from dbo.sysobjects where id = object_id(N'[dbo].[TableSpace]') and object ...

  7. 【github问题】error: src refspec master does not match any解决方法|please tell me who you are

    http://www.open-open.com/lib/view/open1366080269265.html这个先记录一下省得以后再找 我这里要解决的问题根本是:please tell me wh ...

  8. 微信禁用右上角的分享按钮,WeixinJSBridge API以及隐藏分享的子按钮等菜单项

    <!--禁用微信分享按钮--> <script> function onBridgeReady() { WeixinJSBridge.call('hideOptionMenu' ...

  9. servlet jsp jdbc bootstrarp mvc分层模式实现的第一个项目

    登录注册界面 这是一个注册和登录的界面 用到了前端页面中自带的一点H5的标签和属性---巩固下 邮箱格式 :type="email"  不能为空:  required=" ...

  10. hoops暂时用过的一些方法

    (中文全部为谷歌翻译) HC_EXTERNAL void HC_CDECL HC_Show_Shell HC_PROTO ((HC_KEY, int *, HC_POINT *, int *, int ...