I make a console application that should check the connection to a specific IP and perform certain actions. How to monitor such a connection? Here is a list of all outgoing, how to filter and leave only one?

static void ListAvailableTCPPort(ref ArrayList usedPort) { IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections(); IEnumerator myEnum = tcpConnInfoArray.GetEnumerator(); while (myEnum.MoveNext()) { TcpConnectionInformation TCPInfo = (TcpConnectionInformation)myEnum.Current; Console.WriteLine("{0}", TCPInfo.RemoteEndPoint); usedPort.Add(TCPInfo.LocalEndPoint.Port); } } public static void Main() { ArrayList usedPorts = new ArrayList(); ListAvailableTCPPort(ref usedPorts); Console.ReadKey(); } 
  • By what criteria do you want to sort? - Alexcei Shmakov
  • Console.WriteLine("{0}", TCPInfo.RemoteEndPoint); Corrected data output only to the final SP: port. I want to choose from this list only one connection (for example: 127.0.0.1 LI3937) - Elizaveta

1 answer 1

If you need to check connections to a specific IP address, then you should filter
1. The RemoteEndPoint field indicates the IP address and port of the TCP connection that interests you.
2. The connection must have a state ( State ) - Established , which means that the connection is established and data can be sent.

Here is a sample code:

  static void SearchAvailableTCPConnection(ref ArrayList usedPort, string searchAddress, int searchPort) { IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); IPEndPoint filterEndpoint = new IPEndPoint(IPAddress.Parse(searchAddress), searchPort); TcpConnectionInformation tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections().Where(g => g.RemoteEndPoint.Equals(filterEndpoint) && g.State ==TcpState.Established).FirstOrDefault(); if (tcpConnInfoArray != null) { Console.WriteLine("Port {0} {1} {2} ", tcpConnInfoArray.LocalEndPoint, tcpConnInfoArray.RemoteEndPoint, tcpConnInfoArray.State); } } private static void Main(string[] args) { ArrayList usedPorts = new ArrayList(); SearchAvailableTCPConnection(ref usedPorts, "192.168.0.2", 8090); Console.ReadKey(); } 

A message will be displayed on the screen only if we have an active TCP connection with the IP address 192.168.0.2 on port 8090.

To convert the string IP address to the class IPAddress , use the static function of this class Parser .

  • @ Elizabeth, corrected, lost the bracket. - Alexcei Shmakov
  • Found Skype connection on 223.104.3.150:62866, SearchAvailableTCPPort(ref usedPorts, "223.104.3.150", 62866); the console is silent - Elizabeth
  • I also tried the internal ip of another application 192.168.0.61Lin8499, the console is also silent (( - Elizaveta
  • @Elizaveta, updated, should work. - Alexcei Shmakov
  • Sorry, I did not notice. Thank you! Everything worked out! - Elizaveta