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, "請輸入正確的域名,或者您的電腦沒有聯互聯網"); } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM