我希望以编程方式杀死正在占用特定端口的正在运行的IIS实例,但似乎无法确定IIS实例使用的是哪个特定端口。
netstat.exe只是显示进程有PID 4,但这是系统进程。"netsh http显示urlacl“根本不显示被占领的端口。
IIS Express Tray程序不知何故知道这一点。当我试图在端口被占用时启动另一个instance实例时,我会得到以下错误:
“进程‘’已经在使用端口'40000‘(进程ID '10632')。
有人知道我是怎么得到这些信息的吗?
发布于 2017-11-14 21:46:14
PID似乎是4(系统),因为实际侦听套接字位于名为http的服务下。
我查看了iisexpresstray.exe用于提供所有正在运行的IISExpress应用程序的列表。幸运的是,它是托管的.NET代码(全部是iisexpresstray.dll),很容易被解压缩。
它似乎至少有三种不同的方法来获取进程的端口号:
/port
(据我们所知不可靠)netsh http show servicestate view=requestq
并解析输出Microsoft.Web.RuntimeStatusClient.GetWorkerProcess(pid)
并解析站点URL不幸的是,iisexpresstray.dll中大多数有用的东西(比如IisExpressHelper
类)都被声明为internal
(尽管我认为有一些工具可以生成包装器或复制程序集并发布所有信息)。
我选择使用Microsoft.Web.dll。它在我的GAC中,尽管出于某种原因,它没有出现在Visual中可作为引用添加的程序集列表中,所以我只是从GAC中复制出文件。一旦我有了Microsoft.Web.dll,就只需要使用以下代码:
using (var runtimeStatusClient = new RuntimeStatusClient())
{
var workerProcess = runtimeStatusClient.GetWorkerProcess(process.Id);
// Apparently an IISExpress process can run multiple sites/applications?
var apps = workerProcess.RegisteredUrlsInfo.Select(r => r.Split('|')).Select(u => new { SiteName = u[0], PhysicalPath = u[1], Url = u[2] });
// If we just assume one app
return new Uri(apps.FirstOrDefault().Url).Port;
}
还可以调用RuntimeClient.GetAllWorkerProcesses
只检索实际的辅助进程。
我还查看了RegisteredUrlsInfo
(在Microsoft.Web.dll中),发现它使用了两个COM接口,
IRsca2_Core
(F90F62AB-EE00-4E4F-8EA6-3805B6B25CDD
)IRsca2_WorkerProcess
(B1341209-7F09-4ECD-AE5F-3EE40D921870
)最后,我读到Microsoft.Web.Administration的一个版本显然能够读取IISExpress应用程序信息,但是信息非常缺乏,而且我在系统上找到的信息甚至不允许我在没有管理权限的情况下实例化ServerManager
。
发布于 2018-06-29 03:42:52
下面是@makhdumi建议的调用netsh.exe的一个netsh.exe实现:
使用:
static public bool TryGetCurrentProcessRegisteredHttpPort(out List<int> ports, out Exception ex)
{
NetshInvoker netsh = new NetshInvoker();
return netsh.TryGetHttpPortUseByProcessId(Process.GetCurrentProcess().Id, out ports, out ex);
}
Implementation:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace YourCompanyName.Server.ServerCommon.Utility
{
/// <summary>
/// Invoke netsh.exe and extract information from its output.
/// Source: @crokusek, https://stackoverflow.com/questions/32196188
/// @GETah, https://stackoverflow.com/a/8274758/538763
/// </summary>
public class NetshInvoker
{
const string NetshHttpShowServiceStateViewRequestqArgs = "http show servicestate view=requestq";
public NetshInvoker()
{
}
/// <summary>
/// Call netsh.exe to determine the http port number used by a given windowsPid (e.g. an IIS Express process)
/// </summary>
/// <param name="windowsPid">For example an IIS Express process</param>
/// <param name="port"></param>
/// <param name="ex"></param>
/// <returns></returns>
public bool TryGetHttpPortUseByProcessId(Int32 windowsPid, out List<Int32> ports, out Exception ex)
{
ports = null;
try
{
if (!TryQueryProcessIdRegisteredUrls(out Dictionary<Int32, List<string>> pidToUrlMap, out ex))
return false;
if (!pidToUrlMap.TryGetValue(windowsPid, out List<string> urls))
{
throw new Exception(String.Format("Unable to locate windowsPid {0} in '{1}' output.",
windowsPid, "netsh " + NetshHttpShowServiceStateViewRequestqArgs));
}
if (!urls.Any())
{
throw new Exception(String.Format("WindowsPid {0} did not reference any URLs in '{1}' output.",
windowsPid, "netsh " + NetshHttpShowServiceStateViewRequestqArgs));
}
ports = urls
.Select(u => new Uri(u).Port)
.ToList();
return true;
}
catch (Exception ex_)
{
ex = ex_;
return false;
}
}
private bool TryQueryProcessIdRegisteredUrls(out Dictionary<Int32, List<string>> pidToUrlMap, out Exception ex)
{
if (!TryExecNetsh(NetshHttpShowServiceStateViewRequestqArgs, out string output, out ex))
{
pidToUrlMap = null;
return false;
}
bool gotRequestQueueName = false;
bool gotPidStart = false;
int currentPid = 0;
bool gotUrlStart = false;
pidToUrlMap = new Dictionary<int, List<string>>();
foreach (string line in output.Split('\n').Select(s => s.Trim()))
{
if (!gotRequestQueueName)
{
gotRequestQueueName = line.StartsWith("Request queue name:");
}
else if (!gotPidStart)
{
gotPidStart = line.StartsWith("Process IDs:");
}
else if (currentPid == 0)
{
Int32.TryParse(line, out currentPid); // just get the first Pid, ignore others.
}
else if (!gotUrlStart)
{
gotUrlStart = line.StartsWith("Registered URLs:");
}
else if (line.ToLowerInvariant().StartsWith("http"))
{
if (!pidToUrlMap.TryGetValue(currentPid, out List<string> urls))
pidToUrlMap[currentPid] = urls = new List<string>();
urls.Add(line);
}
else // reset
{
gotRequestQueueName = false;
gotPidStart = false;
currentPid = 0;
gotUrlStart = false;
}
}
return true;
}
private bool TryExecNetsh(string args, out string output, out Exception exception)
{
output = null;
exception = null;
try
{
// From @GETah, https://stackoverflow.com/a/8274758/538763
Process p = new Process();
p.StartInfo.FileName = "netsh.exe";
p.StartInfo.Arguments = args;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
output = p.StandardOutput.ReadToEnd();
return true;
}
catch (Exception ex)
{
exception = ex;
return false;
}
}
}
}
发布于 2022-11-24 09:59:52
在我的例子中,我只是输出任务管理器中的“命令行”列,这一点越来越明显,哪个IISExpress是:
https://stackoverflow.com/questions/32196188
复制相似问题