文本框仅允许文本框中的IP地址c#

时间:2016-06-14 08:56:36

标签: c# textbox ip

我试图让文本框只允许IP地址而无需使用互联网进行验证。我将拥有一个"私有的无效textBox3_TextChanged"或者" timer1_Tick"做的工作。每次我打字或打勾时,都会检查它是否有效。这就是为什么我希望它快速,只使用一个简单的本地代码来检查它是否有效,这意味着0.0.0.0 - 255.255.255.255。

首先,它不应该做任何事情,但是当写入ip时,它将启动一个计时器,然后检查ip是否可达。这样做的目的是,当写入IP时,如果在大约4秒后无法访问ip,则图片框将变为红色,如果它可以到达,它将变为绿色,然后停止直到" textbox3_TextChanged"

我试过类似ping的东西,但如果没有输入任何内容就会崩溃,如果无法访问ip则会出现滞后现象:

private void timer1_Tick(object sender, EventArgs e)
    {
        Ping pingSender = new Ping();
        PingOptions options = new PingOptions();

        options.DontFragment = false;


        // Create a buffer of 32 bytes of data to be transmitted.
        string data = "ping";
        byte[] buffer = Encoding.ASCII.GetBytes(data);
        int timeout = 120;
        PingReply reply = pingSender.Send(textBox3.Text, timeout, buffer, options);
        if (reply.Status == IPStatus.Success)
        {
            pictureBox4.BackColor = Color.LimeGreen;
        }
        else
            pictureBox4.BackColor = Color.Red;
    }

以下是截图:http://imgur.com/Cvix2Tr

请帮助:)

1 个答案:

答案 0 :(得分:1)

您可以尝试用以下内容替换textbox3_TextChanged

(对于此示例,我的界面有一个名为textBox的TextBox和一个名为textBlock的TextBlock

//async to not freeze the UI
private async void TextBox_OnTextChanged(object sender, TextChangedEventArgs e)
{
    Ping pingSender = new Ping();
    var tb = (TextBox)sender;

    //a little regex to check if the texbox contains a valid ip adress (ipv4 only).
    //This way you limit the number of useless calls to ping.
    Regex rgx = new Regex(@"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$");
    if (rgx.IsMatch(tb.Text))
    {
        int timeout = 120;
        try
        {
            var reply = await pingSender.SendPingAsync(tb.Text, timeout);
            textBlock.Text = reply.Status == IPStatus.Success ? "OK" : "KO";
        }          
        catch (Exception ex) when (ex is TimeoutException || ex is PingException)
        {
            textBlock.Text = "KO";
        }
    }
    else
    {
        if (textBlock != null)
        {
            textBlock.Text = "Not valid ip";
        }
    }
}