Search code examples
c#string

Validate whether a string is valid for IP Address or not


As title, I want to validate whether a string is valid for IP Address or not in C#, and I've used

IPAddress.TryParse(value out address)

but it seems not so "Accurate", which means if I enter "500", the address will be "0.0.1.244", so its "Valid".

However, the form I'd like to accept is like "xxx.xxx.xxx.xxx", and each term is less than 256. Is there any API or method could achieve this?


Solution

  • You can pretty straightforward check it: split string to parts separated by dot and ensure it will be exactly four parts having values in range 1...255:

    string s = "123.123.123.123";
    
    var parts = s.Split('.');
    
    bool isValid = parts.Length == 4
                   && !parts.Any(
                       x =>
                       {
                           int y;
                           return Int32.TryParse(x, out y) && y > 255 || y < 1;
                       });