获取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,如需转载请自行联系原作者

相关文章
|
30天前
|
Linux 虚拟化 Windows
Linux、Windows上还不会端口映射的网工,请低调看过来!
Linux、Windows上还不会端口映射的网工,请低调看过来!
|
18天前
|
网络协议 Linux
Linux查看端口监听情况,以及Linux查看某个端口对应的进程号和程序
Linux查看端口监听情况,以及Linux查看某个端口对应的进程号和程序
94 2
|
12天前
|
网络协议 C语言
C语言 网络编程(十三)并发的TCP服务端-以进程完成功能
这段代码实现了一个基于TCP协议的多进程并发服务端和客户端程序。服务端通过创建子进程来处理多个客户端连接,解决了粘包问题,并支持不定长数据传输。客户端则循环发送数据并接收服务端回传的信息,同样处理了粘包问题。程序通过自定义的数据长度前缀确保了数据的完整性和准确性。
|
20天前
|
网络协议
Mac根据端口查询进程id的命令
这篇文章介绍了在Mac操作系统上如何使用两种命令来查询监听特定端口的进程ID。第一种方法是使用`netstat -anp tcp -v | grep 端口号`,例如`netstat -anp tcp -v | grep 80`,这将列出所有使用端口80的TCP连接及其相关信息。第二种方法是使用`lsof -P -n -i:端口号`,例如`lsof -P -n -i:8080`,这将显示使用指定端口的进程列表,包括进程ID、用户、文件描述符等信息。文章通过示例展示了如何使用这些命令,并提供了输出结果的截图。
24 2
|
28天前
|
网络协议 网络安全 Python
电脑中 TCP/UDP 端口是否开放的测试:令人意想不到的神奇策略等你发现!
【8月更文挑战第19天】在网络管理和维护中,常需确认TCP/UDP端口是否开放以确保服务运行顺畅。端口如同计算机对外通信的“门”,TCP提供可靠连接,UDP则快速但无连接。测试端口是否开放的方法多样:可用`telnet`测试TCP端口,如`telnet localhost 80`;UDP测试较复杂,可用`nc`工具,如`nc -u -z localhost 53`。此外,也有在线工具可供选择,但需确保其安全性。
40 1
|
30天前
|
网络协议 Windows
在电脑上测试TCP/UDP端口是否开放,还是得网络大佬这招厉害!
在电脑上测试TCP/UDP端口是否开放,还是得网络大佬这招厉害!
|
1月前
|
Windows
Windows中如何查看被占用的端口、杀掉对应的进程
这篇文章介绍了在Windows系统中如何查看被占用的端口号以及如何杀掉占用端口的进程,包括使用命令提示符的`netstat -ano | findstr 端口号`命令查找进程PID,然后通过任务管理器或`taskkill /PID PID号`命令来结束进程。
Windows中如何查看被占用的端口、杀掉对应的进程
|
22天前
|
开发框架 .NET Linux
【Azure 应用服务】 部署到App Service for Linux 服务的Docker 镜像,如何配置监听端口呢?
【Azure 应用服务】 部署到App Service for Linux 服务的Docker 镜像,如何配置监听端口呢?
|
1月前
|
网络协议
【qt】TCP的监听 (设置服务器IP地址和端口号)
【qt】TCP的监听 (设置服务器IP地址和端口号)
72 0
|
1月前
|
Windows
Windows——80端口被系统占用
Windows——80端口被系统占用
34 0