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

C#获取本机可用端口相关推荐

  1. Golang 随机获取本机可用端口

    // 获取可用端口 func GetAvailablePort() (int, error) {address, err := net.ResolveTCPAddr("tcp", ...

  2. Linux Shell脚本 Linux C程序 获取指定的范围内 or 系统可用端口

    Linux Shell脚本 && Linux C程序 获取指定的范围内 or 系统可用端口 一.源代码及其运行 1. Linux C程序getPort.c 源码 运行示例 2. 脚本文 ...

  3. .net core获取本机IP地址

    传统使用中,一般使用下面方法 //获取本机可用的IP地址 var ips = Dns.GetHostAddresses(Dns.GetHostName()).Where(x => x.Addre ...

  4. java 获取已有字体,java获取本机全部可用字体

    java获取本机所有可用字体 //just for fun,那个28个字母的函数满满都是恶心 import java.awt.GraphicsEnvironment ; class Tester { ...

  5. Java 网络实例一(获取指定主机的IP地址、查看端口是否已使用、获取本机ip地址及主机名、获取远程文件大小)

    获取指定主机的IP地址 import java.net.InetAddress; import java.net.UnknownHostException;public class GetIP {pu ...

  6. java 通过snmp协议获取物理机CPU、内存容量及使用率,存储的容量及使用率

    java 用snmp协议获取物理机CPU.内存容量及使用率,存储的容量及使用率,java获取trap告警 一.SNMP简介 1.什么是snmp 二.SNMP获取信息步骤 1.开启SNMP 2.MIB文 ...

  7. java获取本机IP,系统随机分配端口号,获取当前线程ID

    ServerSocket serverSocket = null; //读取空闲的可用端口 String localIp = null; try {serverSocket = new ServerS ...

  8. Unity中获取本机IP地址的方法

    做OptiTrack局域网数据通信时,需要设置本地IP和动捕数据服务器IP,来实现获取动捕数据.由于局域网搭建时需要手动设置电脑IP,因此想到如果可以获取本机IP,服务器IP通常设置固定后不会更改,如 ...

  9. python获取mac、计算机id_python 获取本机IP、mac地址、计算机名的简单示例

    这篇文章主要为大家详细介绍了python 获取本机IP.mac地址.计算机名的简单示例,具有一定的参考价值,可以用来参考一下. 对python获取本机IP.mac地址.计算机名感兴趣的小伙伴,下面一起 ...

最新文章

  1. linux webrtc浏览器,WebRTC 浏览器支持
  2. 基于Android Studio搭建hello world工程
  3. SteamVR追踪技术有多火? 半数开发者来自非游戏行业
  4. sql 实现两行数据作差
  5. [独库骑行之我们穿过草原]巴音布鲁克大草原
  6. c语言中穷竭算法,hihocoder#1054 : 滑动解锁(深度优先搜索)
  7. window server 安装与卸载
  8. javascript第三天(2)
  9. [HEOI2016TJOI2016]排序(二分+线段树)
  10. linux+tar+man,Linux常用命令
  11. 23模式之: 工厂方法模式demo
  12. Java回调网址_极光短信- 回调接口 - 极光文档
  13. Android中的隐藏API和Internal包的使用之获取应用电量排行
  14. 企业如何用好云、管好云?
  15. 发送ajax的get请求,AJAX之发送GET请求
  16. 2019 年我是怎么熬过来的?
  17. 探险家开发者 Niek Bokkers 的故事 | #IMakeApps
  18. numpy - 数组随机排序
  19. 推荐几款不错的企业网站,前端设计师寻求设计灵感!
  20. 日记app(1.0)进展报告

热门文章

  1. 简述如何书写工程化的简单代码
  2. Scott Mitchell 的ASP.NET 2.0数据教程之四十五::DataList和Repeater数据排序(三)
  3. python 字符串和时间格式(datetime)相互转换-
  4. cocos2d-x 3.0正式版创建project笔记
  5. windows2008(64位)下iis7.5中的url伪静态化重写(urlrewrite)
  6. redis live 如何安装
  7. gitlab+keepalived
  8. SpringBoot------Servlet3.0的注解自定义原生Listener监听器
  9. 字符串转Unicode码
  10. MySQL-InnoDB引擎