开发者

Check if a port is assigned to any program or added in firewall - C#

开发者 https://www.devze.com 2023-04-06 10:38 出处:网络
We have Windows Service which will be installed by installer. We have an option to allow user to provide a port number a开发者_开发技巧nd select whether the service must start on completion of install

We have Windows Service which will be installed by installer. We have an option to allow user to provide a port number a开发者_开发技巧nd 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)


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 like String.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.


Finally got the answer by doing some R&D

string OP = @"C:\Windows\Temp\ExceptionList.txt";

ProcessStartInfo procStartInfo = null;

string command = "netsh advfirewall firewall show rule name=all > " + OP;
procStartInfo = new ProcessStartInfo("cmd", "/c " + command);

procStartInfo.CreateNoWindow = true;
procStartInfo.WindowStyle = ProcessWindowStyle.Hidden;

System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
proc.WaitForExit();

if (File.Exists(OP))
{
    StreamReader SR = new StreamReader(OP);
    string FileData = SR.ReadToEnd();
    SR.Close();

    //Logic to read the output and then fetch only records which are enabled and have LocalPort
}

Output (ExceptionList.txt) file contains data in this format

Rule Name:                            NETTCP
---------------------------------------------
Enabled:                              Yes
Direction:                            In
Profiles:                             Domain
Grouping:                             
LocalIP:                              Any
RemoteIP:                             Any
Protocol:                             TCP
LocalPort:                            8080
RemotePort:                           Any
Edge traversal:                       No
Action:                               Allow
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号