C#判断端口是否连接



        //portNum :端口号

        private bool isSetPort(int portNum)
        {
            string ipAddress = getIpAddress();
            System.Net.IPAddress myIpAddress = IPAddress.Parse(ipAddress);
            IPEndPoint point = new IPEndPoint(myIpAddress, portNum);

            try
            {
                using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    sock.Connect(point);
                    return true;
                }
            }
            catch (SocketException ex)
            {
                return false;
            }
        }

        private string getIpAddress()
        {
            try
            {
                System.Net.IPHostEntry localhost = System.Net.Dns.GetHostByName(Dns.GetHostName());
                IPAddress localaddr = localhost.AddressList[0];
                return localaddr.ToString();
            }
            catch (Exception ex)
            {
                return " ";
            }
        }

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页