当我们要创建一个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. Delphi控件之---UpDown以及其与TEdit的配合使用(比如限制TEdit只能输入数字,还有Object Inspector之组件属性的介绍)

    最近在开发中使用到了UpDown这个控件,但是因为之前没有使用过,所以很不熟悉,于是就编写了一个简单的demo来学习UpDown以及其结合TEdit的用法. 初步的常用功能的简介 目前(2015.08 ...

  2. Ubuntu菜鸟入门(九)—— 支付宝支付控件安装

    一.下载 使用支付宝的时候会提示下载 二.安装 1.打开到下载目录 2.使用命令 tar -zxvf aliedit.tar.gz ./aliedit.sh

  3. C# 4.0四大新特性代码示例与解读

    摘要:今天我们结合代码实例来具体看一下C#4.0中的四个比较重要的特性. 之前的文章中,我们曾介绍过C#的历史及C# 4.0新增特性,包括:dynamic. 命名和可选参数.动态导入以及协变和逆变等. ...

  4. RPC原理及RPC实例分析

    在学校期间大家都写过不少程序,比如写个hello world服务类,然后本地调用下,如下所示.这些程序的特点是服务消费方和服务提供方是本地调用关系. 1 2 3 4 5 6 public class ...

  5. 【Python装饰者】在函数测试的作用

    [引言] 我们经常需要多函数进行耗时测试,测试方法有许多,这里介绍装饰者的方法,提高耗时测试代码的可复用性,在其他方面的应用也是如此. [设计原则] 类应该对扩展开放,对修改关闭. [代码] (1)定 ...

  6. 【原】iOS学习之PINCache第三方缓存框架

    在项目中总是需要缓存一些网络请求数据以减轻服务器压力,业内也有许多优秀的开源的解决方案.通常的缓存方案都是由内存缓存和磁盘缓存组成的,内存缓存速度快容量小,磁盘缓存容量大速度慢可持久化. 1.PINC ...

  7. 『AngularJS』$location 服务

    项目中关于 $location的用法 简介 $location服务解析在浏览器地址栏中的URL(基于window.location)并且让URL在你的应用中可用.改变在地址栏中的URL会作用到$loc ...

  8. nodejs express 安装

    前几天刚遇到的问题sudo npm install -g expresssudo npm install -g express-generator然后通过express -V查看版本,看好是大写的V ...

  9. bzoj2002弹(dan)飞绵羊 分块水过

    据说是道lct求深度的题 但是在小猫大的指点下用分块就n^1.5水过了 = =数据忘记加强系列 代码极其不美观,原因是一开始是听小猫大讲的题意,还以为是弹到最前面... #include <cs ...

  10. 【BZOJ2442】 [Usaco2011 Open]修剪草坪 斜率优化DP

    第一次斜率优化. 大致有两种思路: 1.f[i]表示第i个不选的最优情况(最小损失和)f[i]=f[j]+e[i] 显然n^2会T,但是可以发现f的移动情况可以用之前单调队列优化,就优化成O(n)的了 ...