查看端口连接状态

时间:2020-12-27 15:21:10

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.ServiceModel.Description;
using System.Text;
using System.Threading.Tasks;

namespace Client
{
class Program
{
static void Main(string[] args)
{
var portList = new List<int>();
portList.Add(
3389);
portList.Add(
5900);
portList.Add(
1500);

var portDic = GetConnectionsStatus(portList);

foreach (var kvp in portDic)
{
Console.WriteLine(
"如下端口已经建立连接, 连接信息为:port = {0}, remote = {1}", kvp.Key, GetHostNameByIp(kvp.Value.Address.ToString()));
}

Console.WriteLine();
Console.ReadLine();
}

public static Dictionary<int, IPEndPoint> GetConnectionsStatus(List<int> portList)
{
var myDictionary = new Dictionary<int, IPEndPoint>();

var properties = IPGlobalProperties.GetIPGlobalProperties();
var connections = properties.GetActiveTcpConnections();
string ip = GetLocalIp();

foreach (var t in connections)
{
if (t.State == TcpState.Established
&& t.LocalEndPoint.Address.ToString() == ip
&& portList.Contains(t.LocalEndPoint.Port))
{
myDictionary.Add(t.LocalEndPoint.Port, t.RemoteEndPoint);
}
}
return myDictionary;
}

static string GetLocalIp()
{
string hostname = Dns.GetHostName();//得到本机名
IPHostEntry localhost = Dns.GetHostByName(hostname);//只得到IPv4的地址
//IPHostEntry localhost = Dns.GetHostEntry(hostname);//IPv4和IPV6地址
IPAddress localaddr = localhost.AddressList[0];
return localaddr.ToString();
}

public static string GetHostNameByIp(string ip)
{
ip
= ip.Trim();
if (ip == string.Empty)
return string.Empty;
try
{
// 是否 Ping 的通
//if (this.Ping(ip))
// {
System.Net.IPHostEntry host = System.Net.Dns.GetHostEntry(ip);
return host.HostName;
// }
//else
// return string.Empty;
}
catch (Exception)
{
return string.Empty;
}
}
}
}