首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在C#中确定Windows进程使用的tcp端口

要在C#中确定Windows进程使用的TCP端口,您可以使用以下方法:

  1. 使用System.Net.NetworkInformation.IPGlobalProperties类获取TCP连接信息。
  2. 遍历所有TCP连接,检查进程ID(PID)是否与目标进程匹配。
  3. 获取与目标进程关联的TCP端口。

以下是一个示例代码:

代码语言:csharp
复制
using System;
using System.Linq;
using System.Net.NetworkInformation;
using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        int targetProcessId = 12345; // 将此值更改为要查询的进程ID
        IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
        TcpConnectionInformation[] connections = properties.GetActiveTcpConnections();

        foreach (TcpConnectionInformation connection in connections)
        {
            if (connection.OwningProcessId == targetProcessId)
            {
                Console.WriteLine($"进程ID {targetProcessId} 使用了本地端口:{connection.LocalEndPoint.Port}");
            }
        }
    }
}

这段代码将显示与目标进程关联的所有本地TCP端口。请注意,您需要以管理员身份运行此程序才能获取其他进程的TCP连接信息。

在这个示例中,我们没有使用任何云计算品牌商,而是使用了C#编程语言和.NET框架的内置库。这是一个完全自主的解决方案,不依赖于任何第三方库或云服务。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券