System.Net.NetworkInformation命名空间下提供IPGlobalProperties类,用来提供本地计算机有关的网络连接信息,获取本机可用端口的使用方式如下:
using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.NetworkInformation; using System.Linq; namespace Common { public class AvailablePort { private const int MaxPort= 65535; /// <summary> /// 获取所有可用的TCP端口 /// </summary> /// <param name="startPort"></param> /// <returns></returns> public static List<int> GetAllAvailableTCPPort(int startPort = 1000) { //提供本地计算机有关网络连接信息 IPGlobalProperties iPGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); //获取可用的TCP监听终结点信息 IPEndPoint[] iPEndPoints = iPGlobalProperties.GetActiveTcpListeners(); return iPEndPoints.Where(q => q.Port >= startPort && q.Port <= MaxPort).Select(q => q.Port).ToList(); } /// <summary> /// 获取所有可用的UDP端口 /// </summary> /// <param name="startPort"></param> /// <returns></returns> public static List<int> GetAllAvailableUDPPort(int startPort = 1000) { //提供本地计算机有关网络连接信息 IPGlobalProperties iPGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); //获取可用的UDP监听终结点信息 IPEndPoint[] iPEndPoints = iPGlobalProperties.GetActiveUdpListeners(); return iPEndPoints.Where(q => q.Port >= startPort && q.Port <= MaxPort).Select(q => q.Port).ToList(); } /// <summary> /// 获取所有TCP连接 /// </summary> /// <param name="startPort"></param> /// <returns></returns> public static void GetAllTCPConnect(int startPort = 1000) { //提供本地计算机有关网络连接信息 IPGlobalProperties iPGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); //获取TCP连接信息 TcpConnectionInformation[] iPEndPoints = iPGlobalProperties.GetActiveTcpConnections(); foreach (var item in iPEndPoints) { Console.WriteLine($"Local:{item.LocalEndPoint.Address},Remote:{item.RemoteEndPoint.Address},State:{item.State}"); } } } }
原文:https://www.cnblogs.com/lcawen/p/14743983.html