I am rewriting one of my windows service(C#) in Golang. I have almost figured out and rewrote the code in Go but got stuck at one place where I am not been able to figure out golang alternative.
public static int GetNumberOfLocalEstablishedConnectionsByPort(string IPAddress, int Port)
{
int Result = 0;
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] tcpConnections = ipProperties.GetActiveTcpConnections();
foreach (TcpConnectionInformation tcpInfo in tcpConnections)
{
if (tcpInfo.State == TcpState.Established && tcpInfo.LocalEndPoint.Port == Port)
{
Result++;
}
}
return Result;
}
Basically in this method I am finding out active number of connections based on a IP address and Port.
I am seeking help in order to find out how can I rewrite this C# code into Golang. I am using windows OS and want a solution based on Windows OS
In order to find the number of active connections, there is no equivalent wrapper similar to above-mentioned C#
methods in Golang
.
Though we can achieve this using the syscalls for this we can use the following command if you are Linux user.
netstat -anp | grep :80 | grep ESTABLISHED | wc -l
However, in windows os, you might face some problem because grep
and wc
(word count) command will not work. I faced this problem when I ran it as a windows service.
For Windows OS the following command worked.
netstat -nt | findstr :80 | findstr ESTABLISHED | find /v /c ""
For /v /c to work you might need to make the exe file execute as administrator .