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, "请输入正确的域名,或者您的电脑没有联互联网"); } }