开发者

How to find if an IP address falls in a range specified using a pattern? - ASP.NET

If I have an IP address: 192.100.100.2 and need to ensure that it falls within a range specified using wildcard patterns.

The patterns can be either:

 1. 192. *. *. *
 2. *. *. *. *
 3. 192开发者_Go百科.1**. *.2

So essentially, an asterisk or three asterisks specify the valid range. Is there something built in in ASP.NET I can use to validate the IP address or would this be more of a custom validation?


As @AtoMerZ said, just convert your patterns to regular expressions:

    ''//Patterns to search for
    Dim Patterns() As String = {"192.*.*.*", "*.*.*.*", "192.1**.*.2"}

    ''//Test IP
    Dim TestIP = "192.100.100.2"

    ''//Loop through each pattern
    For Each P In Patterns
        ''//Swap two asterisk for two regex digits (\d\d) and one asterisk for one or more digits. Also escape the period
        Trace.WriteLine(System.Text.RegularExpressions.Regex.IsMatch(TestIP, P.Replace("**", "\d\d").Replace("*", "\d+").Replace(".", "\.")))
    Next


Convert it to string and use Regex.Match


Use this validation expression

ValidationExpression="\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]?)\b"

example code

<asp:TextBox ID="TextBox1" runat="server" Width="321px"></asp:TextBox> 
<asp:Button ID="Button1" runat="server" Text="Validate" />
<br />
<asp:RegularExpressionValidator ValidationExpression="\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]?)\b"
    ID="RegularExpressionValidator1" runat="server" ErrorMessage="Invalid IP !" ControlToValidate="TextBox1"></asp:RegularExpressionValidator></div>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜