C# 获取windows下端口占用与进程名称

复制代码
void Main()
{
    GetNetStatPorts().OrderBy(item=> int.Parse(item.port_number))
        .Where(item=>item.name.StartsWith("LINQPad.UserQuery")).Dump();
}

// ===============================================
// The Method That Parses The NetStat Output
// And Returns A List Of Port Objects
// ===============================================
public static List<Port> GetNetStatPorts()
{
    var Ports = new List<Port>();

    try
    {
        using (Process p = new Process())
        {

            ProcessStartInfo ps = new ProcessStartInfo();
            ps.Arguments = "-a -n -o";
            ps.FileName = "netstat.exe";
            ps.UseShellExecute = false;
            ps.WindowStyle = ProcessWindowStyle.Hidden;
            ps.RedirectStandardInput = true;
            ps.RedirectStandardOutput = true;
            ps.RedirectStandardError = true;

            p.StartInfo = ps;
            p.Start();

            StreamReader stdOutput = p.StandardOutput;
            StreamReader stdError = p.StandardError;

            string content = stdOutput.ReadToEnd() + stdError.ReadToEnd();
            string exitStatus = p.ExitCode.ToString();

            if (exitStatus != "0")
            {
                // Command Errored. Handle Here If Need Be
            }

            //Get The Rows
            string[] rows = Regex.Split(content, "\r\n");
            foreach (string row in rows)
            {
                //Split it baby
                string[] tokens = Regex.Split(row, "\\s+");
                if (tokens.Length > 4 && (tokens[1].Equals("UDP") || tokens[1].Equals("TCP")))
                {
                    string localAddress = Regex.Replace(tokens[2], @"\[(.*?)\]", "1.1.1.1");
                    Ports.Add(new Port
                    {
                        protocol = localAddress.Contains("1.1.1.1") ? String.Format("{0}v6", tokens[1]) : String.Format("{0}v4", tokens[1]),
                        port_number = localAddress.Split(':')[1],
                        process_name = tokens[1] == "UDP" ? LookupProcess(Convert.ToInt32(tokens[4])) : LookupProcess(Convert.ToInt32(tokens[5]))
                    });
                }
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    return Ports;
}

public static string LookupProcess(int pid)
{
    string procName;
    try { procName = Process.GetProcessById(pid).ProcessName; }
    catch (Exception) { procName = "-"; }
    return procName;
}

// ===============================================
// The Port Class We're Going To Create A List Of
// ===============================================
public class Port
{
    public string name
    {
        get
        {
            return string.Format("{0} ({1} port {2})", this.process_name, this.protocol, this.port_number);
        }
        set { }
    }
    public string port_number { get; set; }
    public string process_name { get; set; }
    public string protocol { get; set; }
}
// Define other methods and classes here
复制代码

 

posted on   空明流光  阅读(1405)  评论(1编辑  收藏  举报

编辑推荐:
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8
点击右上角即可分享
微信分享提示