C# 判断域名或ip+端口号 是否能正常连接?

复制代码
   private static ManualResetEvent TimeoutObject = new ManualResetEvent(false);

        /// <summary> 
        /// Socket连接请求       
        /// </summary>     
        ///<param name="remoteEndPoint">网络端点</param>      
        ///<param name="timeoutMSec">超时时间</param> 
        public static void Connect(IPEndPoint remoteEndPoint, int timeoutMSec)
        {
            TimeoutObject.Reset();
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.BeginConnect(remoteEndPoint, CallBackMethod, socket);
            //阻塞当前线程           
            if (TimeoutObject.WaitOne(timeoutMSec, false))
            {
                //MessageBox.Show("网络正常");
                Console.WriteLine("网络正常");
            }
            else
            {
                //MessageBox.Show("连接超时");
                Console.WriteLine("连接超时");
            }
        }

        //--异步回调方法       
        private static void CallBackMethod(IAsyncResult asyncresult)
        {
            //使阻塞的线程继续        
            TimeoutObject.Set();

        }

        private delegate string ConnectSocketDelegate(IPEndPoint ipep, Socket sock);
        private string ConnectSocket(IPEndPoint ipep, Socket sock)
        {
            string exmessage = "";
            try
            {
                sock.Connect(ipep);
            }
            catch (System.Exception ex)
            {
                exmessage = ex.Message;
            }
            finally
            {
            }

            return exmessage;
        }

        static void Main(string[] args)
        {
            string domain = "rfid.belle.cn";
            Tuple<bool, string> result = GetDomainIP(domain);
            if (result.Item1) {
                IPAddress ip = IPAddress.Parse(result.Item2);
                IPEndPoint ipep = new IPEndPoint(ip, 900);//IP和端口

                Connect(ipep,  6000);
            }

            Console.ReadLine();
        }


        private static Tuple<bool, string> GetDomainIP(string domain)
        {
           
            try
            {
                string Result = domain;//提取域名地址
                IPHostEntry host = Dns.GetHostByName(Result);//域名解析的IP地址
                IPAddress ip = host.AddressList[0];
                string rIP = ip.ToString();
                return Tuple.Create(true, rIP);
            }
            catch
            {
                return Tuple.Create(false, "请输入正确的域名,或者您的电脑没有联互联网");
            }
        }
复制代码

 

posted @   大空白纸  阅读(2204)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
历史上的今天:
2014-11-04 C# redis简单的使用
点击右上角即可分享
微信分享提示