Feedback

prüfen ob String eine gültige IP ist

Sprache: C#

Mit dieser Funktion wird geprüft, ob der übergebene String ein Gültige IP Adresse ist. Bsp: "0.0.0.0" bis "255.255.255.255" ist gültig "1.2.3.256" oder "0.0.2" ist ungültig
/// <summary>
/// Determines whether the specified string is an IP address.
/// </summary>
/// <param name="IP">The string.</param>
/// <returns>
/// 	<c>true</c> if the specified IP is IP; otherwise, <c>false</c>.
/// </returns>
private bool IsIP(string IP)
{
    return System.Text.RegularExpressions.Regex.IsMatch(IP, @"b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$b");
}
/// <summary>
/// Determines whether the specified string is an IP address.
/// </summary>
/// <param name="IP">The string.</param>
/// <returns>
/// 	<c>true</c> if the specified IP is IP; otherwise, <c>false</c>.
/// </returns>
private bool IsIP(string IP)
{
    return System.Text.RegularExpressions.Regex.IsMatch(IP, @"b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$b");
}

4 Kommentare

  1. Hallo, für meine Begriffe gehört ganz hinen noch ein $ dran, ansonsten ist auch „1.2.3.4abc“ eine gültige IP Adresse.
    Gruß aus Bottrop

  2. Um es leserlicher zu machen, würde ich es so schreiben. Ist aber reine Geschmackssache.
    [code]
    const string From0To199 = „[01]?[0-9][0-9]?“;
    const string From200To249 = „2[0-4][0-9]“;
    const string From250To255 = „25[0-5]“;
    const string OneIPPlace = „(“ + From250To255 + „|“ + From200To249 + „|“ + From0To199 + „)“;

    private bool IsIP(string IP)
    {
    return System.Text.RegularExpressions.Regex.IsMatch(IP, „\b(“ + OneIPPlace + „\.){3}“ + OneIPPlace + „$\b“);
    }
    [/code]