C# 判断本机端口有没有被占用

直接上代码

public static bool IsPortInUse(int port)
    {
        bool isPortInUse = false;
        IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
        IPEndPoint[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpListeners();
        IPEndPoint[] udpConnInfoArray = ipGlobalProperties.GetActiveUdpListeners();

        foreach (IPEndPoint endPoint in tcpConnInfoArray)
        {
            if (endPoint.Port == port)
            {
                isPortInUse = true;
                break;
            }
        }

        if (!isPortInUse)
        {
            foreach (IPEndPoint endPoint in udpConnInfoArray)
            {
                if (endPoint.Port == port)
                {
                    isPortInUse = true;
                    break;
                }
            }
        }

        return isPortInUse;
    }

调用方式:

 1 int port = 80; // 要检查的端口号
 2         bool isPortInUse = PortChecker.IsPortInUse(port);
 3         if (isPortInUse)
 4         {
 5             Console.WriteLine($"端口 {port} 被占用.");
 6         }
 7         else
 8         {
 9             Console.WriteLine($"端口 {port} 未被占用.");
10         }

 

posted @ 2024-02-20 18:00  Yanaha  阅读(503)  评论(0)    收藏  举报