C# 判斷域名或ip +端口號 是否能連接


 
static void Main(string[] args)
        {
            var item = GetDomainIP("http://aaaaa.com");
            if (item.Item1)
            {
                AddressPort(item.Item2, 3389);
            }
        }
        private static Tuple<bool, string> GetDomainIP(string url)
        {
            string ipAddress = url;
            if (!ipAddress.StartsWith("http"))
            {
                ipAddress = "http://" + ipAddress;
            }
            string p = @"(http|https)://(?<domain>[^(:|/]*)";
            Regex reg = new Regex(p, RegexOptions.IgnoreCase);
            Match m = reg.Match(ipAddress);
            try
            {
                string Result = m.Groups["domain"].Value;//提取域名地址 
                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, "請輸入正確的域名,或者您的電腦沒有聯互聯網");
            }
        }
        private static void AddressPort(string ipAddress, int portNum)
        {
            try
            {
                IPAddress ip = IPAddress.Parse(ipAddress);
                IPEndPoint point = new IPEndPoint(ip, portNum);
                using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    sock.Connect(point);
                    Console.WriteLine("連接{0}成功!", point);
                    sock.Close();
                }
            }
            catch (SocketException e)
            {
           
            }
        }

   部分代碼來源:http://www.luofenming.com/show.aspx?id=ART2017122600002

       

  注意:遠程桌面連接端口默認值是3389


免責聲明!

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



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