0

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

Abhishek Soni
  • 1,677
  • 4
  • 20
  • 27
  • 1
    You'll likely have to use syscalls to get this done, there is no native Go wrapper for this Windows-specific functionality. – Adrian Oct 10 '17 at 19:55
  • 1
    Using `syscall` on .NET DLL's is not the same as the native C++ DLLs. I haven't done this myself, but [this](https://stackoverflow.com/a/44167406/102371) answer points to a github project you may want to investigate. (For completeness [here](https://github.com/matiasinsaurralde/go-dotnet) is the github link) – John Weldon Oct 11 '17 at 00:17
  • other option is trying to find the equivalent of this Linux command `netstat -tulpn` on Windows – Yandry Pozo Oct 11 '17 at 00:28

1 Answers1

0

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 .

Abhishek Soni
  • 1,677
  • 4
  • 20
  • 27