C#判断端口是否连接

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/thanks_hck/article/details/79137866


        //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 " ";
            }
        }

展开阅读全文

没有更多推荐了,返回首页