如何查看当前开放的端口?
时间: 2024-09-09 11:12:11 浏览: 51
详解Linux 查看服务器开放的端口号
5星 · 资源好评率100%
在C#中,要查看当前开放的端口,可以通过调用Windows API来实现。一种方法是使用`System.Diagnostics`命名空间下的`Process`类,结合`TcpListener`和`Socket`类来枚举正在监听的端口。以下是使用C#代码来查看本地计算机上开放端口的示例:
```csharp
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
class Program
{
static void Main()
{
List<IPAddress> localIPs = new List<IPAddress>();
// Add the loopback IP address.
localIPs.Add(IPAddress.Loopback);
// Add IP addresses for all network interfaces on the local machine.
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIPs.Add(ip);
}
}
foreach (IPAddress localIP in localIPs)
{
Console.WriteLine("Interface IP Address: " + localIP.ToString());
IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
// Retrieve TCP connections.
TcpConnectionInformation[] tcpConnInfoArray = properties.GetTcpConnections();
foreach (TcpConnectionInformation tcpConnInfo in tcpConnInfoArray)
{
// Print out the state of the connection.
Console.WriteLine("TCP State: " + tcpConnInfo.State.ToString());
// Print out the local endpoint.
IPEndPoint localEndPoint = tcpConnInfo.LocalEndPoint as IPEndPoint;
if (localEndPoint != null && localEndPoint.Address.Equals(localIP))
{
Console.WriteLine("Local EndPoint: " + localEndPoint.ToString());
}
}
// Retrieve UDP connections.
IPEndPoint[] udpListeners = properties.GetActiveUdpListeners();
foreach (IPEndPoint udpEndPoint in udpListeners)
{
if (udpEndPoint.Address.Equals(localIP))
{
Console.WriteLine("UDP Listener EndPoint: " + udpEndPoint.ToString());
}
}
}
}
}
```
上面的代码会显示所有本地接口的IP地址,并列出每个IP地址上的TCP和UDP监听端口。请注意,这需要在具有管理员权限的环境中运行,因为某些端口信息可能受到安全限制。
阅读全文