检查端口是否分配给任何程序或添加到防火墙中 - C#
我们有 Windows 服务,将由安装程序安装。我们可以选择允许用户提供端口号并选择服务是否必须在安装完成后启动。我们正在检查安装程序本身,以检查端口是否打开/可用。
TcpClient TcpScan = new TcpClient();
TcpScan.Connect("localhost", portno);
if (TcpScan.Connected == true)
{
TcpScan.Close();
}
我的问题是,如果用户选择在安装时不启动服务的选项,然后我们在同一台计算机上安装另一个实例,其端口与第一个实例使用的端口相同,那么如果我们启动这两个服务,那么其中一个服务将不工作。
那么有什么方法可以检查用户提供的端口是否已经存在于防火墙中或者是否已分配给其他一些Windows服务? (还假设服务可以处于停止状态)
We have Windows Service which will be installed by installer. We have an option to allow user to provide a port number and select whether the service must start on completion of installation. We are having a check on installer itself for checking whether the port is open/available.
TcpClient TcpScan = new TcpClient();
TcpScan.Connect("localhost", portno);
if (TcpScan.Connected == true)
{
TcpScan.Close();
}
My problem is if the user selects the option of not to start the service on installation and then we install another instance on the same machine with the same port as used in first one, then if we start both the services then one of the service will not work.
So is there any way I can check whether the port provided by user is already there in firewall or is already assigned to some other windows service? (Also assume the service can be in stopped state)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
得到了答案
最后通过做一些研发输出(ExceptionList.txt)文件包含这种格式的数据
Finally got the answer by doing some R&D
Output (ExceptionList.txt) file contains data in this format
我认为不会,因为任何应用程序都可以在运行时打开端口。
例如,您可以使用
Mutex
来避免同一端口上的多个服务实例(为互斥体指定类似String.Format(MyMutex_{0},my_port}.
您可以/应该在服务启动期间检查该端口是否空闲,如果不是则正常关闭它。
I think no, because any app could open a port at runtime.
You can (for example) use a
Mutex
to avoid multiple instances of your service on the same port (giving the mutex a name likeString.Format(MyMutex_{0},my_port}
.And you could/should check if that port is free during service startup and close it gracefully if it's not.