简体   繁体   中英

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?

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;
                   });

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 _));
}

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;
    }

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 .

string addrString = "192.168.0.1";
IPAddress address;
if (IPAddress.TryParse(addrString, out address)) {
       //Valid IP, with address containing the IP
} else {
       //Invalid IP
}

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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM