我在尝试确定地址是IP地址还是主机名时遇到问题。 我发现的一切都说使用正则表达式。我不知道如何形成IF声明。这是我的代码:
private void btnPingAddress_Click(object sender, EventArgs e)
{
intByteSize = Convert.ToInt32(numericDataSize.Value);
intNumberOfPings = Convert.ToInt32(numericPing.Value);
strDnsAddress = cmbPingAddress.Text;
//If address is IP address:
if (strDnsAddress Contains ((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?")
{
txtPingResults.Text = "Pinging " + strIpAddress + " with " + intByteSize + " bytes of data:" + "\r\n";
}
// If address is hostname:
else
{
strIpAddress = Convert.ToString(Dns.GetHostEntry(strDnsAddress));
txtPingResults.Text = "Pinging " + strDnsAddress + " [" + strIpAddress + "] with " + intByteSize + " bytes of data:" + "\r\n";
}
Ping ping = new Ping();
PingReply reply = ping.Send(cmbPingAddress.Text);
txtPingResults.Text = "Pinging " + cmbPingAddress.Text + " [" + Convert.ToString(reply.Address) + "] with " + intByteSize + " bytes of data:" + "\r\n";
for (int i = 0; i < intNumberOfPings; i++)
{
txtPingResults.AppendText("Reply from "+Convert.ToString(reply.Address)+": Bytes="+Convert.ToString(intByteSize) +" Time="+Convert.ToString(reply.RoundtripTime) +"ms"+" TTL="+Convert.ToString(reply.Options.Ttl)+ "\r\n");
cmbPingAddress.Items.Add(cmbPingAddress.Text);
}
}
非常感谢任何帮助。
答案 0 :(得分:3)
我最近需要这样做以拆分WebAPI标头。 Uri.CheckHostName
可能是最简单的方法,它包括ipv6支持:
var dns = Uri.CheckHostName("www.google.com"); //UriHostNameType.Dns
var ipv4 = Uri.CheckHostName("192.168.0.1"); //IPv4
var ipv6 = Uri.CheckHostName("2601:18f:780:308:d96d:6088:6f40:c5a8");//IPv6
dns = Uri.CheckHostName("Foo"); //Dns
最后一个很棘手,但在技术上是正确的。至少,您可以排除主机名与IP地址。
答案 1 :(得分:2)
尝试:
ValidIpAddressRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";
ValidHostnameRegex = "^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$";
if(Regex.IsMatch(strDnsAddress, ValidIpAddressRegex )) {
// the string is an IP
}
else if(Regex.IsMatch(strDnsAddress,ValidHostnameRegex )){
// the string is a host
}
答案 2 :(得分:1)
使用你的正则表达式:
if(Regex.IsMatch(strDnsAddress, "(2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?")) {
// the string is an IP
}
或者你可以使用this问题中提供的正则表达式(正如habib zare在他的评论中所建议的那样)
答案 3 :(得分:0)
我试图以一种非常基本且易于理解的初学者来解释这个概念!
注意::函数的参数定义为可选参数(CheckHost(string host="127.0.0.0")
)
public static void CheckHost(string host="127.0.0.1")
{
if (host == null || host.Length == 0)
{
Console.WriteLine("no host is defined!");
}
else if (Uri.CheckHostName(host).ToString() == "Dns")
{
Console.WriteLine("The "+host+" is a DNS hostname.");
}
else if (Uri.CheckHostName(host).ToString() == "IPv4")
{
Console.WriteLine("The " + host + " is an IP Address v4.");
}
else if (Uri.CheckHostName(host).ToString() == "IPv6")
{
Console.WriteLine("The " + host + " is an IP Address v6.");
}
else
{
Console.WriteLine("The " + host + " is unknown!");
}
}