2012-08-16 129 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地址。

相關問題