usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Net;usingSystem.Net.NetworkInformation;usingSystem.ServiceModel.Description;usingSystem.Text;usingSystem.Threading.Tasks;namespaceclient{classProgram {Static voidMain (string[] args) { varPortlist =Newlist<int>(); Portlist.add (3389); Portlist.add (5900); Portlist.add ( the); varPortdic =Getconnectionsstatus (portlist); foreach(varKvpinchportdic) {Console.WriteLine ("The following port is already connected with the connection information: Port = {0}, remote = {1}", kvp. Key, Gethostnamebyip (kvp. Value.Address.ToString ())); } Console.WriteLine (); Console.ReadLine (); } Public Staticdictionary<int, Ipendpoint> Getconnectionsstatus (list<int>portlist) { varMyDictionary =Newdictionary<int, ipendpoint>(); varProperties =ipglobalproperties.getipglobalproperties (); varConnections =Properties. Getactivetcpconnections (); stringIP =Getlocalip (); foreach(varTinchconnections) { if(T.state = =tcpstate.established&& t.localendpoint.address.tostring () = =IP&&portlist.contains (T.localendpoint.port)) {Mydictionary.add (T.localendpoint.port, t.remoteendpoint); } } returnMyDictionary; } Static stringGetlocalip () {stringhostname = Dns.gethostname ();//get the name of the machineIphostentry localhost = dns.gethostbyname (hostname);//just get IPv4 's address.//iphostentry localhost = dns.gethostentry (hostname);//IPv4 and IPV6 addressIPAddress localaddr = localhost. addresslist[0]; returnlocaladdr. ToString (); } Public Static stringGethostnamebyip (stringIP) {IP=IP. Trim (); if(IP = =string. Empty)return string. Empty; Try { //whether the Ping is a pass//if (this. Ping (IP))// {System.Net.IPHostEntry host =System.Net.Dns.GetHostEntry (IP); returnhost. HostName; // } //Else//return string. Empty; } Catch(Exception) {return string. Empty; } } }}
View Port Connection Status