2

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?

Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
Alanight
  • 353
  • 2
  • 8
  • 23

6 Answers6

4

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;
                   });
Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
4

Something like that:

private static Boolean IsIP(String value) {
  if (String.IsNullOrEmpty(value))
    return false;

  var items = value.Split('.');

  if (items.Length != 4)
    return false;

  // Simplest: you may want use, say, NumberStyles.AllowHexSpecifier to allow hex as well
  return items.All(item => byte.TryParse(item, out _));
}
Todd Menier
  • 37,557
  • 17
  • 150
  • 173
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • Frankly, checking each part of address with `Byte.TryParse` is not sufficient, since 0 will be successfully parsed as byte, so this will consider "0.0.1.244" as valid address. – Andrey Korneyev May 25 '15 at 11:08
  • @AndyKorneyev `0` is valid. Ever heard of `127.0.0.1`? – Magnus May 25 '15 at 11:11
3

If you dont rely on TryParse here is one way to match for xxx.xxx.xxx.xxx

public static bool MyIP(string value)
    {
        var x = value.Split('.');
        if (!(x.Length==4)) 
           return false;

        foreach(var i in x) 
        {
            int q;
            if (!Int32.TryParse(x, out q)||q.ToString().Length.Equals(x.Length) 
                || q < 0 || q > 255) 
            { 
               return false;  
            }

        }

        return true;
    }
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
2

If you'd rather not do the parsing yourself the NuGet package IPAddressRange will do it for you. It has the advantage of supporting IPv6 addresses as well.

You can check out the source code and documentation here.

Matt Brooks
  • 1,584
  • 1
  • 14
  • 27
-1
string addrString = "192.168.0.1";
IPAddress address;
if (IPAddress.TryParse(addrString, out address)) {
       //Valid IP, with address containing the IP
} else {
       //Invalid IP
}
Omkar Hendre
  • 397
  • 3
  • 12
-1

You could try what you are already doing, with a short test before hand to ensure there are the correct number of "."s in the string. https://msdn.microsoft.com/en-us/library/system.net.ipaddress.tryparse.aspx

It will determine if string is valid IPv4 address, this will not work for IPv6:

var stringToCheck = "192.168.1.1";
var countDots = stringToCheck.Split('.').Length - 1;
if (countDots==3)
{
    IPAddress validIpAddress;
    if (IPAddress.TryParse(stringToCheck, out validIpAddress))
    {
        //Valid IP, with validIpAddress containing the IP
        Console.WriteLine("Valid IP");
    }
    else
    {
        //Invalid IP
        Console.WriteLine("Invalid IP");
    }
}
else
{
    // Invalid as no "." in string, not even worth checking
    Console.WriteLine("Invalid IP not correct number Dots");
}
DermFrench
  • 3,968
  • 13
  • 43
  • 70