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