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();
}
}
}
}
.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#获取本机可用端口的更多相关文章
- C#动态获取本机可用串口的两种方式
1. private void GetSerialPort() //获取串口列表 { RegistryKey keyCom = Registry.LocalMachine.OpenSubKey(&qu ...
- C++ Socket 获取本机可用端口号(QT)
:加载套接字库,创建套接字(WSAStartup()/socket()): :绑定套接字到一个IP地址和一个端口上(bind()): :将套接字设置为监听模式等待连接请求(listen()): :请求 ...
- C# — 动态获取本地IP地址及可用端口
1.在VS中动态获取本地IP地址,代码如下: 2.获取本机的可用端口以及已使用的端口:
- 用C++和shell获取本机CPU、网卡IO、内存、磁盘等的基本信息
用C++和shell获取本机CPU.网卡.内存.磁盘等的基本信息: 由于对C++相关的函数没多少了解,但是觉得用shell反而相对简单一些: 一.shell脚本,用来辅助C++获取主机的资源使用信息 ...
- C#获取本机磁盘信息
照着书敲的.留作笔记吧. using System; using System.Collections.Generic; using System.Linq; using System.Text; u ...
- 获取本机IP、mac地址、计算机名
python获取本机IP.mac地址.计算机名 在python中获取ip地址和在php中有很大不同,我们先来看一下python 获得本机MAC地址: >>> import uuid ...
- python获取本机IP、mac地址、计算机名
在python中获取ip地址和在php中有很大不同,在php中往往比较简单.那再python中怎么做呢? 我们先来看一下python 获得本机MAC地址: 1 2 3 4 import uuid de ...
- 获取本机CPU,硬盘等使用情况
早上的时候接到主管的一个任务,要获取服务器上的cpu,硬盘, 数据库等 的使用情况,并以邮件的方式发给boss, = =没办法,公司的服务器真是不敢恭维,顺便吐槽一下公司的网速,卡的时候30k左右徘徊 ...
- 如何获取本机IP
GetLocalHost 直接通过InetAddress.getLocalHost()来获取,其主要逻辑如下 InetAddress.getLocalHost(): String hostname = ...
随机推荐
- Dark Mobile Bank之移动银行应用仿冒攻击威胁分析报告
一.背景 据“第十五次全国信息网络安全状况暨计算机和移动终端病毒疫情调查”调查结果显示,2015年移动终端的病毒感染比例为50.46%,相对于2014年增长了18.96%,移动终端病毒感染率涨幅较大, ...
- MongoDB的分片(9)
什么是分片 分片是指将数据库拆分,将其分散在不同的机器上的过程.将数据分散到不同的机器上,不需要功能强大的服务器就可以存储更多的数据和处理更大的负载.基本思想就是将集合切成小块,这些块分散到若干片里, ...
- 闪回查询(SELECT AS OF)
使用Flashback Query的场景包括如下: 摘自官档 Recovering lost data or undoing incorrect, committed changes. For exa ...
- Datazen图表创建和发布
Datazen是被微软收购的移动端全平台的数据展现解决方案.此篇主要介绍如何创建和发布图表. 如前面介绍,Datazen图表的创建和发布是通过Publisher的应用,它是Windows 8应用商店下 ...
- java 的 struts2 Spring Hibernate 三大框架的整合
原理就不说了,直接上配置文件及代码,用来备用 首先,将三大框架所需要的jar包导入项目中 导入 struts2-spring-plugin-2.3.3.jar包 此包的作用是作为struts2 与 ...
- ubuntu 用apt-get 安装apache 和php 之后php不能解析的问题
sudo apt-get install apache2 sudo apt-get install php7.0 sudo apt-get install libapache2-mod-php //关 ...
- $(document).ready,$(window).load,window.onload区别和联系
$(document).ready是在dom结构加载完毕就执行. $(window).load 等价于window.onload,必须等到页面内包括图片的所有元素加载完毕后才能执行. $(docume ...
- 诡异的localhost无法连接
上午试了localhost发现提示无法连接,ping了下localhost,能够ping通. 重启了Apache,还是无法解决. 试着停止了Apache服务,然后再连接localhost,发现浏览器提 ...
- 全本软件白名单 Quanben Software Whitelist
Windows应用软件 Windows Applications (TBU) 全本推荐微软Windows 10操作系统 Quanben recommends Microsoft Windows 10 ...
- 德国W家HIPP 奶粉有货播报:2014.6.25 HIPP 1+ 4盒装有货啦!
德国W家HIPP 奶粉有货播报:2014.6.25 HIPP 1+ 4盒装有货啦!