C#怎么判断域名是否合法

zn3051644 2012-10-30 10:08:27
C#怎么判断域名是否合法
...全文
649 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
心灵彩虹 2012-10-30
  • 打赏
  • 举报
回复 1

1\关于域名解析 作用:可以把域名转换成IP地址

[csharp] view plaincopyprint?
using System.Net;

public static string domain2ip(string str)
{
string _return = "";
try
{
IPHostEntry hostinfo = Dns.GetHostByName(str);
IPAddress[] aryIP = hostinfo.AddressList;
_return = aryIP[0].ToString();

}
catch (Exception e)
{
_return = e.Message;
}
return _return;
}
using System.Net;

public static string domain2ip(string str)
{
string _return = "";
try
{
IPHostEntry hostinfo = Dns.GetHostByName(str);
IPAddress[] aryIP = hostinfo.AddressList;
_return = aryIP[0].ToString();

}
catch (Exception e)
{
_return = e.Message;
}
return _return;
}

2 正则式匹配 作用:验证一个字串是否符合IP规则

using System.Text.RegularExpressions;

Match m = Regex.Match(ip, "(//d{1,3}//.){3}//d{1,3}");

if (m.Success)
data_ip = ip;//IP合法
else
{ //IP不合法
lab_prompt.Text = "服务器连接失败...";
this.btn_login.Enabled = false;
}
心灵彩虹 2012-10-30
  • 打赏
  • 举报
回复 1

C# 正则域名
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace rexurl
{
class Program
{
static void Main(string[] args)
{
string regex = @"(?i)http://(\w+\.){2,3}(com(\.cn)?|cn|net)\b";
string content = "http://www.17meiman.com/u/20090313/15/5ad5d3f2-094f-4b01-9c91-a6d4052a8255.html";
Regex re1 = new Regex(regex);
MatchCollection matches = re1.Matches(content);
System.Collections.IEnumerator enu = matches.GetEnumerator();

while (enu.MoveNext() && enu.Current != null)
{

Match match = (Match)(enu.Current);
string str = match.Value;
Console.Write(str);

}
Console.Read();
}
}
}


  • 打赏
  • 举报
回复
string input = Console.ReadLine();
bool b=Regex.IsMatch(input,"[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+.?")
if(b)
Console.WriteLine("合法");
else
Console.WriteLine("不合法");

111,125

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧