当我们要创建一个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. javascript 转盘抽奖代码和计数器代码

    要介绍了javascript圆盘抽奖程序实现原理和完整代码例子,需要的朋友可以参考下  看到网页上有不少大转盘抽奖的应用,心血来潮也想弄个.于是找了点资料自己研究...  效果预览: 一.模拟抽奖的实 ...

  2. js获取浏览器body或窗宽度高度合集

    <script type="text/javascript"> var s = " "; document.documentElement.scro ...

  3. asp.net core的TagHelper简单使用

    TagHelper(标签助手)是ASP.NET Core非常好的一种新特性.可以扩展视图,让其看起来像一个原生HTML标签. 应该使用TagHelper替换HtmlHelper,因其更简洁更易用,且支 ...

  4. 提高 ASP.NET Web 应用性能

    转载:http://www.codeceo.com/article/24-ways-improve-aspnet-web.html 在这篇文章中,将介绍一些提高 ASP.NET Web 应用性能的方法 ...

  5. java中的throw与throws的区别

    什么时运行时异常?什么是非运行时异常? 通俗的讲: 运行时异常:就是编译通过,运行时就崩了,比如数组越界. 非运行时异常:就是编译不通过,这时就得必须去处理了.不然就没法运行了. 全面的讲: Thro ...

  6. selenium使用笔记(三)——元素定位

    selenium进行自动化测试的一个很重要的东西那就是元素定位,如果元素都没法定位就无法操作它,也就无法进行自动化测试了.网上对于元素定位有很多的介绍,很详细很详细的,但是依然有很多新手总是会遇到无法 ...

  7. 【Hawk】高级教程——post参数采集万方医学网论文

    目标——万方医学网论文列表 http://med.wanfangdata.com.cn/Author/General/A000000001 和普通网页不一样的地方在于点击下一页的时候,URL没有发生变 ...

  8. XE版本 InputQuery 可以同时填多个输入值

    function InputQuery(const ACaption: string; const APrompts: array of string; var AValues: array of s ...

  9. 图片Base64编码

    我们经常在做Jquery插件的时候需要插入一些自定义的控件,比如说按钮,而我们自己又觉着button标签很丑,而且不同浏览器显示的效果还不一样,这个时候我们需要用到图片,当然,我们可以通过img标签添 ...

  10. 解决nginx中proxy_pass到tomcat的session丢失问题

    之前在配置tomcat的时候都是一个项目对应一个tomcat,也就是一个端口.最近需要把两个项目整合到同一个tomcat中,通过配置nginx让两个域名指向同一tomcat的不同项目.整合完毕后发现其 ...