2012-08-16 130 views
0

我在尝试确定地址是IP地址还是主机名时遇到问题。 我发现的一切都说使用正则表达式。我不确定如何形成IF声明。这里是我的代码:确定组合框文本是IP地址还是主机名

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); 
    } 
} 

任何帮助将不胜感激。

+3

不要忘记也支持IPv6地址。 – 2012-08-16 01:14:39

回答

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 

} 
+3

您应该使用逐字字符串来定义那些不会编译的正则表达式 – BlackBear 2012-08-16 01:28:52

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问题所提供的正则表达式(如哈比卜在他的评论扎雷建议)

2

我需要最近这样做是为了拉开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地址。

相关问题