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");
}
Alte URL:
/snippet/pruefen-ob-string-eine-gueltige-ip-ist/106
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
ooops,
sollte heißen „1.2.3.4 abc“ statt „1.2.3.4abc“ (mit einem blank dazwischen)
und (natürlich) hinten statt hinen!
Hallo,
Danke für den Hinweis. Ich habe den Fehler korrigiert.
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]