10

I tried this code for validating IP address, but it doesn't work...

public static bool IP(string ipStr)
{
    string pattern = @"^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$";
    Regex check = new Regex (pattern);
    bool valid = false;
    if (ipStr == "") {
        valid = false;
    } else {
        valid = check.IsMatch (ipStr, 0);
    }
    return valid;
}   

Any idea what's wrong?

Roy Goode
  • 2,940
  • 20
  • 22
MojoDK
  • 4,410
  • 10
  • 42
  • 80
  • 14
    "*Any idea what's wrong?*" Not until you tell us what "doesn't work" means. – ildjarn Feb 06 '12 at 19:24
  • Why need regex to validate IP? A simple `string.Split()`, `Int.Parse()` would do it. – Shiplu Mokaddim Feb 06 '12 at 19:27
  • 1
    you need to clarify WHAT doesn't work. I built out a test for this regex and it seems to grab the ip with some unusual grouping, but it works none-the-less. – deltree Feb 06 '12 at 19:27
  • 4
    You cannot realistically validate an IP address with a regex. 10.0, 172.16.0, 0177.00000.0x0.1, 0x7F000001, 017700000001, and 2130706433 are all valid IP addresses to somebody, while 4294967296 is clearly illegal. By the time your regex is sufficient to accept 4294967295 and reject 4294967297 you're not really in regex space any longer. – Old Pro May 19 '13 at 07:58
  • Anything that can be expressed with a finite state machine is "regex space". – Bojidar Stanchev Jun 09 '20 at 14:42

6 Answers6

63

I would use IPAddress.TryParse static method instead.

IPAddress ip;
bool b = IPAddress.TryParse("1234.12.12.12",out ip);
Austin Salonen
  • 49,173
  • 15
  • 109
  • 139
L.B
  • 114,136
  • 19
  • 178
  • 224
  • 5
    Great answer. Solved the problem with an existing and easier to read solution. +1 – Razor Feb 07 '12 at 00:53
  • 3
    This method produces some rather strange results. Entering just integers will validate. For example: IPAddress.TryParse("255555",out ip) will return true with the IP address of: {0.3.230.67} – Dave Hogan Aug 02 '12 at 12:51
  • 6
    @DaveHogan It is not strange and completely legal. `IPAddress.TryParse("2130706433", out ip);` and `IPAddress.TryParse("0x7f000001", out ip);` are, for example, another representation for `127.0.0.1` – L.B Aug 02 '12 at 15:02
  • 3
    I read the documentation and noticed that it accepts octal, decimal, and hexadecimal input. It's definitely something to be aware of when validating input. If someone enters the numeric value 1 into my field I would expect it to error not assume the IP was 0.0.0.1 – Dave Hogan Aug 02 '12 at 15:14
  • 1
    @DaveHogan I assume anyone who is entering an IPv4 address is aware that it's just a 32 bit integer like every other 32 bit integer out there. If someone tried dotted decimal notation `"127.0.0.1"` and typoed, it will fail unless they happened to miss all three dots - highly unlikely. If they enter a bogus value like "1", and it doesn't work 'normally', I would suggest your users stop entering bogus values. – corsiKa Aug 27 '12 at 19:55
  • 1
    +1 - sad to say, as an experienced c# developer, i had never used IPAddress.TryParse before. This saved me from mangling up convoluted regexes that would have been pretty hard to maintain - thank you. – jim tollan May 01 '15 at 08:23
  • 2
    TryParse is not bullet proof for testing the IP address, look at the remarks in the documentation: https://learn.microsoft.com/de-de/dotnet/api/system.net.ipaddress.tryparse?view=netcore-1.1 – John Doe Sep 21 '17 at 10:48
7

for match a valid IP adress use

^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$

instead of

^([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])(\.([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])){3}$

because many regex engine match the first possibility in the OR sequence

you can try your regex engine : 10.48.0.200

test the difference here

Alban
  • 3,105
  • 5
  • 31
  • 46
2

There is a previously answered question available for a valid IP address.

As for debugging regular expressions, on Windows I heartily recommend Expresso. On the web, there is a free Flash-based tester available.

Community
  • 1
  • 1
ern
  • 1,522
  • 13
  • 19
1

Here is the complete regex for checking all possible IPv4 addresses (dotted decimal, dotted hexadecimal, dotted octal, decimal, hexadecimal, octal and mixed mode)

^(0[0-7]{10,11}|0(x|X)[0-9a-fA-F]{8}|(\b4\d{8}[0-5]\b|\b[1-3]?\d{8}\d?\b)|((2[0-5][0-5]|1\d{2}|[1-9]\d?)|(0(x|X)[0-9a-fA-F]{2})|(0[0-7]{3}))(\.((2[0-5][0-5]|1\d{2}|\d\d?)|(0(x|X)[0-9a-fA-F]{2})|(0[0-7]{3}))){3})$

I have tested it with all possible addresses.

Prabhanjan Naib
  • 201
  • 3
  • 12
1

I'm not really a regex expert per se but i use Expresso (a regex tool) and it has it's own regex library for pre-set scenarios like this. Try this below.

string pattern = @"(?<First>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<Second>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<Third>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<Fourth>2[0-4]\d|25[0-5]|[01]?\d\d?)";
scartag
  • 17,548
  • 3
  • 48
  • 52
0

For CIDR format in both ipv4 and ipv6

http://blog.markhatton.co.uk/2011/03/15/regular-expressions-for-ip-addresses-cidr-ranges-and-hostnames/

pepelkod
  • 56
  • 3