获取Windows下某进程监听的TCP/UDP端口

简介:

1、在Windows下用CMD netstat命令可以获得当前进程监听端口号的信息,如netstat -ano可以看到IP、port、状态和监听的PID。

那么可以执行CMD这个进程得到监听的端口号信息,C#代码如下:

复制代码
            //进程id
            int pid = ProcInfo.ProcessID;
            
            //存放进程使用的端口号链表
            List<int> ports = new List<int>();

            Process pro = new Process();
            pro.StartInfo.FileName = "cmd.exe";
            pro.StartInfo.UseShellExecute = false;
            pro.StartInfo.RedirectStandardInput = true;
            pro.StartInfo.RedirectStandardOutput = true;
            pro.StartInfo.RedirectStandardError = true;
            pro.StartInfo.CreateNoWindow = true;
            pro.Start();
            pro.StandardInput.WriteLine("netstat -ano");
            pro.StandardInput.WriteLine("exit");
            Regex reg = new Regex("\\s+", RegexOptions.Compiled);
            string line = null;
            ports.Clear();
            while ((line = pro.StandardOutput.ReadLine()) != null)
            {
                line = line.Trim();
                if (line.StartsWith("TCP", StringComparison.OrdinalIgnoreCase))
                {
                    line = reg.Replace(line, ",");
                    string[] arr = line.Split(',');
                    if (arr[4] == pid.ToString())
                    {
                        string soc = arr[1];
                        int pos = soc.LastIndexOf(':');
                        int pot = int.Parse(soc.Substring(pos + 1));
                        ports.Add(pot);
                    }
                }
                else if (line.StartsWith("UDP", StringComparison.OrdinalIgnoreCase))
                {
                    line = reg.Replace(line, ",");
                    string[] arr = line.Split(',');
                    if (arr[3] == pid.ToString())
                    {
                        string soc = arr[1];
                        int pos = soc.LastIndexOf(':');
                        int pot = int.Parse(soc.Substring(pos + 1));
                        ports.Add(pot);
                    }
                }
            }
            pro.Close();
复制代码

2、如果不执行CMD进程,如何获得?可以参考这篇文章http://www.cnblogs.com/BoyXiao/archive/2012/02/20/2359273.html

文章介绍了使用Windows API获得进程和端口的映射关系:

(1)根据进程 ID 获得该进程所打开的所有的 TCP 和 UDP 端口。

(2)根据端口号来获得打开该端口的进程。

C语言代码如下:

  View Code

如果要在.Net平台下使用,将其编译成DLL,使用PInvoke得到DLL导出函数就可以了。

C#测试代码:

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace ProcessorPortDllTest
{
    public enum TcpOrUdp
    {
        TcpType,
        UdpType
    };

    public class ProcessPortHelper
    {
        [DllImport("ProcessorPort.dll",CallingConvention = CallingConvention.StdCall)]
        public extern static uint GetProcessIdByPort(TcpOrUdp type, uint dwPort);

        [DllImport("ProcessorPort.dll",CallingConvention = CallingConvention.StdCall)]
        public extern static uint GetAllPortByProcessId(TcpOrUdp type, uint dwProcessId, uint[] dwAllPort, uint dwMaxLen);
    }

    class Program
    {
        static void Main(string[] args)
        {
            uint port = 1025;
            uint processorId = ProcessPortHelper.GetProcessIdByPort(TcpOrUdp.TcpType, port);
            Console.WriteLine("Port {0} is using by processor {1}",port,processorId);

            uint processorId1 = 1072;

            uint[] TcpPorts = new uint[100];
            uint count = ProcessPortHelper.GetAllPortByProcessId(TcpOrUdp.TcpType, processorId1, TcpPorts, (uint)TcpPorts.Length);
            Console.WriteLine("Processor {0} is using TCP port: ", processorId1);
            for (uint i = 0; i < count; ++i)
            {
                Console.WriteLine(TcpPorts[i]);
            }

            uint[] UdpPorts = new uint[100];
            uint count1 = ProcessPortHelper.GetAllPortByProcessId(TcpOrUdp.UdpType, processorId1, UdpPorts, (uint)UdpPorts.Length);
            Console.WriteLine("Processor {0} is using UDP port: ", processorId1);
            for (uint i = 0; i < count1; ++i)
            {
                Console.WriteLine(UdpPorts[i]);
            }

Console.ReadKey(); } } }
复制代码

 

获得进程监听TCP/UDP端口号的DLL:ProcessorPort.rar




    本文转自阿凡卢博客园博客,原文链接:http://www.cnblogs.com/luxiaoxun/p/3404176.html,如需转载请自行联系原作者

相关文章
|
17天前
|
网络协议
iptables配置tcp端口转发
iptables配置tcp端口转发
25 1
|
25天前
|
负载均衡 网络协议 算法
slb监听协议与端口
SLB是云服务商提供的负载均衡服务,用于分发客户端请求到多台后端服务器,提升服务可用性和响应速度。关键概念包括监听协议(TCP、UDP、HTTP、HTTPS、TCPSSL)和监听端口。监听协议决定了SLB处理请求的方式,而监听端口则是SLB接收请求的入口。配置时需根据应用选择合适协议和端口,并可设置负载均衡算法(如轮询、最少连接等)。客户端应通过SLB统一入口访问后端服务,避免绕过SLB导致的问题。
43 1
|
29天前
|
负载均衡 网络协议 安全
slb选择监听协议和端口
阿里云SLB中,监听协议(TCP、HTTP、HTTPS)与端口(80、443等)决定客户端请求的处理方式。TCP适用于纯TCP或自处理HTTP的场景,HTTP用于智能调度Web服务,HTTPS提供安全的HTTP传输。监听端口通常匹配应用标准,如80 for HTTP,443 for HTTPS。配置时,可考虑HTTPS重定向和传递`X-Forwarded-Proto`头以识别请求来源。选择应基于业务需求和安全考虑。
29 3
|
3月前
|
Windows
windows环境下根据端口号查询进程编号并杀掉此进程
windows环境下根据端口号查询进程编号并杀掉此进程
|
1月前
|
网络协议
TCP 和 UDP 可以使用同一个端口吗?
【2月更文挑战第9天】
50 0
TCP 和 UDP 可以使用同一个端口吗?
|
2月前
window查看端口占用并关闭对应进程
window查看端口占用并关闭对应进程
|
2月前
|
网络协议
TCP和UDP和端口
TCP和UDP和端口
22 1
|
2月前
|
网络协议 Linux 网络架构
【Cisco Packet Tracer】运输层端口与TCP的作用
【Cisco Packet Tracer】运输层端口与TCP的作用
27 0
|
3月前
|
运维 安全 数据库
cmd中使用telnet检测远程的ip及端口是否处于监听状态
cmd中使用telnet检测远程的ip及端口是否处于监听状态
30 1
|
26天前
|
域名解析 网络协议 关系型数据库
tcp和udp的区别是什么
TCP和UDP是互联网协议中的传输层协议。TCP是面向连接的,通过三次握手建立可靠连接,提供数据顺序和可靠性保证,适用于HTTP、FTP等需要保证数据完整性的应用。UDP则是无连接的,数据报独立发送,传输速度快但不保证可靠性,常用于实时通信、流媒体和DNS解析等对速度要求高的场景。根据应用需求选择合适的协议至关重要。
tcp和udp的区别是什么