1

我需要一个只允许 IP 地址的文本框。我可以在 Web 应用程序中创建它,但不能在 Windows 应用程序中执行此操作。请帮我这样做..

4

3 回答 3

3

使用此方法验证 IP

 public bool IsValidIP(string addr)
    {
        //create our match pattern
        string pattern = @"^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.
([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$";
        //create our Regular Expression object
        Regex check = new Regex(pattern);
        //boolean variable to hold the status
        bool valid = false;
        //check to make sure an ip address was provided
        if (addr == "")
        {
            //no address provided so return false
            valid = false;
        }
        else
        {
            //address provided so use the IsMatch Method
            //of the Regular Expression object
            valid = check.IsMatch(addr, 0);
        }
        //return the results
        return valid;
    }
于 2012-06-07T07:40:07.400 回答
1

您可以使用ASP.NET Regular Expression Validator

<asp:RegularExpressionValidator ID="regexpName" runat="server"     
                                ErrorMessage="This expression does not validate." 
                                ControlToValidate="yourTextBox"     
                                ValidationExpression="RegEx here" />

然后将其设置ValidationExpression为:(仅允许 IP 地址)

\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\
于 2012-06-07T07:35:37.197 回答
0

这里。取文本,用点分隔,如果你最终得到 4 个字节(如 0-255 范围内的数字),它是一个有效的 ip。

bool IsTextAValidIPAddress(string text)
{
    bool result = true;
    string[] values = text.Split(new[] { "." }, StringSplitOptions.None); //keep empty strings when splitting
    result &= values.Length == 4; // aka string has to be like "xx.xx.xx.xx"
    if(result)
        for (int i = 0; i < 4; i++) 
            result &= byte.TryParse(values[i], out temp); //each "xx" must be a byte (0-255)
    return result;
}

或者,如果您可以/想要利用System.Net

bool IsTextAValidIPAddress(string text)
{
    System.Net.IPAddress test;
    return System.Net.IPAddress.TryParse(text,out test);
}
于 2012-06-07T07:53:03.160 回答