zoukankan      html  css  js  c++  java
  • C# 获取本机可用端口

    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}");
                }
            }
        }
    }
  • 相关阅读:
    MySQL数据同步,出现Slave_SQL_Running:no和slave_io_running:no问题的解决方法
    【坑】解决CentOS 7.1版本以上安装好zabbix 3.4 无法重启zabbix-server的问题
    unison+inotify的Web目录同步方案
    vue-cli3.0配置图片转base64的规则
    nginx将http升级到https并且同时支持http和https两种请求、http自动转向https
    linux中使用ps -ef
    form表单input回车提交问题
    Linux创建Jenkins启动脚本以及开机启动服务
    xshell破解
    WebSocket断开原因、心跳机制防止自动断开连接
  • 原文地址:https://www.cnblogs.com/lcawen/p/14743983.html
Copyright © 2011-2022 走看看