如何獲取C#中的開放端口的進程名稱?如何獲取C#中的開放端口的進程名稱?
8
A
回答
4
3
您可以執行netstat -anb
並處理輸出。
2
我不久前有過同樣的問題。沒有一種簡單的方法可以單獨使用.net。您檢索端口號和進程標識符,但不是兩者之間的關係。
這段代碼使用NetStat來解決它。
獲取活動端口和相關的進程名稱在C#
http://www.cheynewallace.com/get-active-ports-and-associated-process-names-in-c/
7
一些搜索,我已經適應潮華萊士的解決方案與返回過程的映射端口的一個屬性的靜態類之後使用NetStat的列表形式。
這裏的類:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
namespace MyNamespace
{
/// <summary>
/// Static class that returns the list of processes and the ports those processes use.
/// </summary>
public static class ProcessPorts
{
/// <summary>
/// A list of ProcesesPorts that contain the mapping of processes and the ports that the process uses.
/// </summary>
public static List<ProcessPort> ProcessPortMap
{
get
{
return GetNetStatPorts();
}
}
/// <summary>
/// This method distills the output from netstat -a -n -o into a list of ProcessPorts that provide a mapping between
/// the process (name and id) and the ports that the process is using.
/// </summary>
/// <returns></returns>
private static List<ProcessPort> GetNetStatPorts()
{
List<ProcessPort> ProcessPorts = new List<ProcessPort>();
try
{
using (Process Proc = new Process())
{
ProcessStartInfo StartInfo = new ProcessStartInfo();
StartInfo.FileName = "netstat.exe";
StartInfo.Arguments = "-a -n -o";
StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
StartInfo.UseShellExecute = false;
StartInfo.RedirectStandardInput = true;
StartInfo.RedirectStandardOutput = true;
StartInfo.RedirectStandardError = true;
Proc.StartInfo = StartInfo;
Proc.Start();
StreamReader StandardOutput = Proc.StandardOutput;
StreamReader StandardError = Proc.StandardError;
string NetStatContent = StandardOutput.ReadToEnd() + StandardError.ReadToEnd();
string NetStatExitStatus = Proc.ExitCode.ToString();
if (NetStatExitStatus != "0")
{
Console.WriteLine("NetStat command failed. This may require elevated permissions.");
}
string[] NetStatRows = Regex.Split(NetStatContent, "\r\n");
foreach (string NetStatRow in NetStatRows)
{
string[] Tokens = Regex.Split(NetStatRow, "\\s+");
if (Tokens.Length > 4 && (Tokens[1].Equals("UDP") || Tokens[1].Equals("TCP")))
{
string IpAddress = Regex.Replace(Tokens[2], @"\[(.*?)\]", "1.1.1.1");
try
{
ProcessPorts.Add(new ProcessPort(
Tokens[1] == "UDP" ? GetProcessName(Convert.ToInt16(Tokens[4])) : GetProcessName(Convert.ToInt16(Tokens[5])),
Tokens[1] == "UDP" ? Convert.ToInt16(Tokens[4]) : Convert.ToInt16(Tokens[5]),
IpAddress.Contains("1.1.1.1") ? String.Format("{0}v6", Tokens[1]) : String.Format("{0}v4", Tokens[1]),
Convert.ToInt32(IpAddress.Split(':')[1])
));
}
catch
{
Console.WriteLine("Could not convert the following NetStat row to a Process to Port mapping.");
Console.WriteLine(NetStatRow);
}
}
else
{
if (!NetStatRow.Trim().StartsWith("Proto") && !NetStatRow.Trim().StartsWith("Active") && !String.IsNullOrWhiteSpace(NetStatRow))
{
Console.WriteLine("Unrecognized NetStat row to a Process to Port mapping.");
Console.WriteLine(NetStatRow);
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return ProcessPorts;
}
/// <summary>
/// Private method that handles pulling the process name (if one exists) from the process id.
/// </summary>
/// <param name="ProcessId"></param>
/// <returns></returns>
private static string GetProcessName(int ProcessId)
{
string procName = "UNKNOWN";
try
{
procName = Process.GetProcessById(ProcessId).ProcessName;
}
catch { }
return procName;
}
}
/// <summary>
/// A mapping for processes to ports and ports to processes that are being used in the system.
/// </summary>
public class ProcessPort
{
private string _ProcessName = String.Empty;
private int _ProcessId = 0;
private string _Protocol = String.Empty;
private int _PortNumber = 0;
/// <summary>
/// Internal constructor to initialize the mapping of process to port.
/// </summary>
/// <param name="ProcessName">Name of process to be </param>
/// <param name="ProcessId"></param>
/// <param name="Protocol"></param>
/// <param name="PortNumber"></param>
internal ProcessPort (string ProcessName, int ProcessId, string Protocol, int PortNumber)
{
_ProcessName = ProcessName;
_ProcessId = ProcessId;
_Protocol = Protocol;
_PortNumber = PortNumber;
}
public string ProcessPortDescription
{
get
{
return String.Format("{0} ({1} port {2} pid {3})", _ProcessName, _Protocol, _PortNumber, _ProcessId);
}
}
public string ProcessName
{
get { return _ProcessName; }
}
public int ProcessId
{
get { return _ProcessId; }
}
public string Protocol
{
get { return _Protocol; }
}
public int PortNumber
{
get { return _PortNumber; }
}
}
}
從一個簡單的控制檯應用程序調用可能看起來像:
using System;
namespace MyNamespace
{
class Program
{
static void Main(string[] args)
{
foreach (ProcessPort p in ProcessPorts.ProcessPortMap.FindAll(x => x.ProcessName.ToLower() == "myprocess")) //extension is not needed.
{
Console.WriteLine(p.ProcessPortDescription);
}
foreach (ProcessPort p in ProcessPorts.ProcessPortMap.FindAll(x => x.PortNumber == 4444))
{
Console.WriteLine(p.ProcessPortDescription);
}
Console.WriteLine("Press any key to continue...");
Console.ReadLine();
}
}
}
+0
進程ID的Int32,不Int16 :) – Nuzzolilo 2014-03-20 08:48:32
相關問題
- 1. 如何獲取c#中的端口名稱?
- 2. 獲取服務名稱的端口號?
- 3. 檢查C/C++中的開放端口
- 4. 獲取進程名稱窗口標題名稱和安裝的軟件名稱
- 5. 如何從進程名稱獲取應用程序名稱?
- 6. 如何從android中的進程獲取應用程序名稱?
- 7. 如何在Windows中獲取進程的應用程序名稱?
- 8. SharpPcap獲取進程名稱
- 9. 如何在PHP中獲取遠程服務器的開放端口?
- 10. 如何使用c#獲取任務欄中應用程序的進程名稱?
- 11. 如何獲取具有可見窗口的任何進程的名稱 - WinAPI?
- 12. 如何通過objective-c獲取iphone上的tcp/udp開放端口列表?
- 13. 如何從PID使用C獲取進程名稱
- 14. 如何在Process Explorer中獲取進程開始地址的「名稱」?
- 15. 如何在C#應用程序中獲取外部窗口的名稱?
- 16. 通過窗口句柄獲取未知進程的名稱?
- 17. 如何獲取生成拖放的應用程序的名稱
- 18. 如何獲取應用程序的進程名稱?
- 19. 如何獲取所有線程ID和進程的名稱
- 20. 如何從進程名稱獲取進程ID?
- 21. 如何獲取C#中進程的開放網絡連接列表?
- 22. 如何在c#中獲取存儲過程的參數名稱
- 23. 獲取mongodb打開連接的進程名稱
- 24. 如何獲取服務器名稱,端口和上下文
- 25. 如何在Windows中獲得COM端口的友好名稱?
- 26. C# - 我如何重命名我開始的進程窗口?
- 27. 如何獲取窗口名稱? [Python]
- 28. 如何獲取進程在監聽的端口?
- 29. 如何獲取Win32線程的名稱?
- 30. 以編程方式獲取友好端口名稱
任何其他的想法......通過.NET或Win32 API的 – 2009-11-04 18:47:19