C#指定指定端口是否已经被占用的代码

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

下面的C#代码定义了一个函数用于判断指定的端口是否已经被占用。
代码转自: http://www.cnblogs.com/smiler/
public static bool PortInUse(int port)
{
    bool inUse = false;
             
    IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
    IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();
             
    foreach (IPEndPoint endPoint in ipEndPoints)
    {
        if (endPoint.Port == port)
        {
            inUse = true;
            break;
        }
    }
 
    return inUse;
}

下面的范例代码占用了8080端口,然后用上面定义的函数检测端口是否被占用
static void Main(string[] args)
{
    HttpListener httpListner = new HttpListener();
    httpListner.Prefixes.Add("http://*:8080/");
    httpListner.Start();
 
    Console.WriteLine("Port: 8080 status: " + (PortInUse(8080) ? "in use" : "not in use"));
 
    Console.ReadKey();
 
    httpListner.Close();
}