Regexp to check if an IP is valid












1















I'm wondering if it's possible to compare values in regexps with the regexp system in Python. Matching the pattern of an IP is easy, but each 1-3 digits cannot be above 255 and that's where I'm a bit stumped.










share|improve this question


















  • 1





    What about IPv6?

    – schot
    Oct 25 '10 at 5:49






  • 1





    It is inferred by the question that the OP wants IPv4 addresses.

    – tzot
    Oct 25 '10 at 7:11


















1















I'm wondering if it's possible to compare values in regexps with the regexp system in Python. Matching the pattern of an IP is easy, but each 1-3 digits cannot be above 255 and that's where I'm a bit stumped.










share|improve this question


















  • 1





    What about IPv6?

    – schot
    Oct 25 '10 at 5:49






  • 1





    It is inferred by the question that the OP wants IPv4 addresses.

    – tzot
    Oct 25 '10 at 7:11
















1












1








1








I'm wondering if it's possible to compare values in regexps with the regexp system in Python. Matching the pattern of an IP is easy, but each 1-3 digits cannot be above 255 and that's where I'm a bit stumped.










share|improve this question














I'm wondering if it's possible to compare values in regexps with the regexp system in Python. Matching the pattern of an IP is easy, but each 1-3 digits cannot be above 255 and that's where I'm a bit stumped.







python regex






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Oct 25 '10 at 4:10









duttdutt

4,13873969




4,13873969








  • 1





    What about IPv6?

    – schot
    Oct 25 '10 at 5:49






  • 1





    It is inferred by the question that the OP wants IPv4 addresses.

    – tzot
    Oct 25 '10 at 7:11
















  • 1





    What about IPv6?

    – schot
    Oct 25 '10 at 5:49






  • 1





    It is inferred by the question that the OP wants IPv4 addresses.

    – tzot
    Oct 25 '10 at 7:11










1




1





What about IPv6?

– schot
Oct 25 '10 at 5:49





What about IPv6?

– schot
Oct 25 '10 at 5:49




1




1





It is inferred by the question that the OP wants IPv4 addresses.

– tzot
Oct 25 '10 at 7:11







It is inferred by the question that the OP wants IPv4 addresses.

– tzot
Oct 25 '10 at 7:11














8 Answers
8






active

oldest

votes


















6














You need to check the allowed numbers in each position. For the first optional digit, acceptable values are 0-2. For the second, 0-5 (if the first digit for that part is present, otherwise 0-9), and 0-9 for the third.



I found this annotated example at http://www.regular-expressions.info/regexbuddy/ipaccurate.html :



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





share|improve this answer
























  • I thought about doing something like that, very neat with an explanation though :) Thanks.

    – dutt
    Oct 25 '10 at 4:23






  • 7





    A good example of when not to use regexes.

    – Glenn Maynard
    Oct 25 '10 at 7:21











  • @Glenn Maynard if you already have the IP and need to check if it's valid, I wouldn't use a regex. If you need to extract potential IPs from blocks of other text, a regex would be useful.

    – JAL
    Oct 25 '10 at 7:28











  • It's a little bit of both, I need to use a regex for this, otherwise I need to add things to the framework and bladiblabla.

    – dutt
    Oct 25 '10 at 10:04



















9














No need for regular expressions here. Some background:



>>> import socket
>>> socket.inet_aton('255.255.255.255')
'xffxffxffxff'
>>> socket.inet_aton('255.255.255.256')
Traceback (most recent call last):
File "<input>", line 1, in <module>
error: illegal IP address string passed to inet_aton
>>> socket.inet_aton('my name is nobody')
Traceback (most recent call last):
File "<input>", line 1, in <module>
error: illegal IP address string passed to inet_aton


So:



import socket

def ip_address_is_valid(address):
try: socket.inet_aton(address)
except socket.error: return False
else: return True


Note that addresses like '127.1' could be acceptable on your machine (there are systems, including MS Windows and Linux, where missing octets are interpreted as zero, so '127.1' is equivalent to '127.0.0.1', and '10.1.4' is equivalent to '10.1.0.4'). Should you require that there are always 4 octets, change the last line from:



else: return True


into:



else: return address.count('.') == 3





share|improve this answer


























  • I thought that zero-filled was only the case with IPv6 addresses and the :: notation? It is frequently the case that when writing IP addresses with a CIDR mask that only the octets touched by the mask are written (10/8, 172.16/12, 192.168/16, 192.168.127/24), with a "zero-fill" on the remaining octets. But eliding zero-octets in the middle I've never seen with IPv4.

    – Vatine
    Oct 25 '10 at 8:17











  • @Vatine: I assume you: a) downvoted my answer because you thought I was stating something mistaken, while I was stating something you didn't know b) you've never pinged 127.1 yourself; please, do try it. Not only I am mistaken, but the creator of your IP stack is mistaken too. We apologize.

    – tzot
    Oct 25 '10 at 8:32











  • @ΤΖΩΤΖΙΟΥ: My ping expands 127.1 into 127.0.0.1 but it was concocted in the Dark Tower of Redmond where adherence to standards is sometimes a little casual so that proves nuffin :-)

    – John Machin
    Oct 25 '10 at 8:55











  • @John: of course it proves nuffin :) My ping —which was concocted in the Evil Forces of *nix— together with your ping just assert that 127.1 is acceptable

    – tzot
    Oct 25 '10 at 9:34













  • Just because the implied empty fields are accepted by some systems does not mean they are correct. That is like saying a single 32bit integer, expressed in decimal is valid, or that hex should be accepted (because some interfaces accept hex for the quads values.

    – benc
    Oct 25 '10 at 15:08



















6














You can check a 4-octet IP address easily without regexes at all. Here's a tested working method:



>>> def valid_ip(ip):
... parts = ip.split('.')
... return (
... len(parts) == 4
... and all(part.isdigit() for part in parts)
... and all(0 <= int(part) <= 255 for part in parts)
... )
...
>>> valid_ip('1.2.3.4')
True
>>> valid_ip('1.2.3.4.5')
False
>>> valid_ip('1.2. 3 .4.5')
False
>>> valid_ip('1.256.3.4.5')
False
>>> valid_ip('1.B.3.4')
False
>>>





share|improve this answer































    3














    Regex is for pattern matching, but to check for a valid IP, you need to check for the range (i.e. 0 <= n <= 255).



    You may use regex to check for range, but that'll be a bit overkill. I think you're better off checking for basic patter and then check for the range for each number.



    For example, use the following pattern to match an IP:



    ([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3})


    Then check whether each number is within range.






    share|improve this answer
























    • Or more compact: (([0-9]{1,3}.){3}[0-9]{1,3})

      – whirlwin
      Feb 15 '11 at 19:38



















    3














    The following supports IPv4, IPv6 as well as Python 2.7 & 3.3



    import socket


    def is_valid_ipv4(ip_str):
    """
    Check the validity of an IPv4 address
    """
    try:
    socket.inet_pton(socket.AF_INET, ip_str)
    except AttributeError:
    try:
    socket.inet_aton(ip_str)
    except socket.error:
    return False
    return ip_str.count('.') == 3
    except socket.error:
    return False
    return True


    def is_valid_ipv6(ip_str):
    """
    Check the validity of an IPv6 address
    """
    try:
    socket.inet_pton(socket.AF_INET6, ip_str)
    except socket.error:
    return False
    return True


    def is_valid_ip(ip_str):
    """
    Check the validity of an IP address
    """
    return is_valid_ipv4(ip_str) or is_valid_ipv6(ip_str)





    share|improve this answer
























    • this is the best answer of all, but for windows users win_inet_pton must be installed, and the import statement should be changed to: try: import win_inet_pton except ImportError: pass import socket

      – StefanNch
      Nov 2 '14 at 10:45



















    0














    IP addresses can also be checked with split as follows,



    all(map((lambda x: 0<=x<=255),map(int,ip.split('.')))) and len(ip.split("."))==4


    For me thats a little bit more readable than regex.






    share|improve this answer
























    • huh, kind of a neat solution too. thanks :)

      – dutt
      Oct 25 '10 at 4:54











    • -2 FAIL on '1. 2 .3.4' and FAIL on '1.B.2.3' @dutt: be suspicious of anything with 2 * map() and excess parentheses and test before use.

      – John Machin
      Oct 25 '10 at 5:46











    • The "readable" expression can be reduced to the equivalent all(map(lambda x: 0<=int(x)<=255,ip.split('.'))) and len(ip.split("."))==4 by removing a map() call and the redundant parentheses around the lambda expression (but still fails, of course)

      – John Machin
      Oct 25 '10 at 5:57











    • @John Machin, I accept that I didn't test for the possibility of spaces (my bad). But '1.B.2.3' test doesn't fail. I get a value error. ValueError: invalid literal for int() with base 10: 'B'

      – Sujoy
      Oct 25 '10 at 15:10











    • crashes instead of returning False. That's not a fail???

      – John Machin
      Oct 25 '10 at 20:40



















    0














    I think people are taking this too far I suggest you first do this:
    ips = re.findall('(?:[d]{1,3}).(?:[d]{1,3}).(?:[d]{1,3}).(?:[d]{1,3})', page)
    then split the 4 numbers where there is a '.' and check and see if they are smaller than 256






    share|improve this answer































      0














      You need this-



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


      Regular expression visualization



      Debuggex Demo






      share|improve this answer


























      • So is 219.1.1.1 a valid or an invalid IP address?

        – tzot
        Oct 2 '14 at 23:46











      • why not, can u explain?

        – Rajesh Paul
        Oct 4 '14 at 6:14











      • Let me rephrase: does 219.1.1.1 (a valid IP address) pass your regex test?

        – tzot
        Oct 4 '14 at 18:49











      • Thanx @tzot, for this correction.

        – Rajesh Paul
        Oct 5 '14 at 4:45












      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4011855%2fregexp-to-check-if-an-ip-is-valid%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      8 Answers
      8






      active

      oldest

      votes








      8 Answers
      8






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      6














      You need to check the allowed numbers in each position. For the first optional digit, acceptable values are 0-2. For the second, 0-5 (if the first digit for that part is present, otherwise 0-9), and 0-9 for the third.



      I found this annotated example at http://www.regular-expressions.info/regexbuddy/ipaccurate.html :



      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





      share|improve this answer
























      • I thought about doing something like that, very neat with an explanation though :) Thanks.

        – dutt
        Oct 25 '10 at 4:23






      • 7





        A good example of when not to use regexes.

        – Glenn Maynard
        Oct 25 '10 at 7:21











      • @Glenn Maynard if you already have the IP and need to check if it's valid, I wouldn't use a regex. If you need to extract potential IPs from blocks of other text, a regex would be useful.

        – JAL
        Oct 25 '10 at 7:28











      • It's a little bit of both, I need to use a regex for this, otherwise I need to add things to the framework and bladiblabla.

        – dutt
        Oct 25 '10 at 10:04
















      6














      You need to check the allowed numbers in each position. For the first optional digit, acceptable values are 0-2. For the second, 0-5 (if the first digit for that part is present, otherwise 0-9), and 0-9 for the third.



      I found this annotated example at http://www.regular-expressions.info/regexbuddy/ipaccurate.html :



      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





      share|improve this answer
























      • I thought about doing something like that, very neat with an explanation though :) Thanks.

        – dutt
        Oct 25 '10 at 4:23






      • 7





        A good example of when not to use regexes.

        – Glenn Maynard
        Oct 25 '10 at 7:21











      • @Glenn Maynard if you already have the IP and need to check if it's valid, I wouldn't use a regex. If you need to extract potential IPs from blocks of other text, a regex would be useful.

        – JAL
        Oct 25 '10 at 7:28











      • It's a little bit of both, I need to use a regex for this, otherwise I need to add things to the framework and bladiblabla.

        – dutt
        Oct 25 '10 at 10:04














      6












      6








      6







      You need to check the allowed numbers in each position. For the first optional digit, acceptable values are 0-2. For the second, 0-5 (if the first digit for that part is present, otherwise 0-9), and 0-9 for the third.



      I found this annotated example at http://www.regular-expressions.info/regexbuddy/ipaccurate.html :



      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





      share|improve this answer













      You need to check the allowed numbers in each position. For the first optional digit, acceptable values are 0-2. For the second, 0-5 (if the first digit for that part is present, otherwise 0-9), and 0-9 for the third.



      I found this annotated example at http://www.regular-expressions.info/regexbuddy/ipaccurate.html :



      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






      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Oct 25 '10 at 4:16









      JALJAL

      17.9k13960




      17.9k13960













      • I thought about doing something like that, very neat with an explanation though :) Thanks.

        – dutt
        Oct 25 '10 at 4:23






      • 7





        A good example of when not to use regexes.

        – Glenn Maynard
        Oct 25 '10 at 7:21











      • @Glenn Maynard if you already have the IP and need to check if it's valid, I wouldn't use a regex. If you need to extract potential IPs from blocks of other text, a regex would be useful.

        – JAL
        Oct 25 '10 at 7:28











      • It's a little bit of both, I need to use a regex for this, otherwise I need to add things to the framework and bladiblabla.

        – dutt
        Oct 25 '10 at 10:04



















      • I thought about doing something like that, very neat with an explanation though :) Thanks.

        – dutt
        Oct 25 '10 at 4:23






      • 7





        A good example of when not to use regexes.

        – Glenn Maynard
        Oct 25 '10 at 7:21











      • @Glenn Maynard if you already have the IP and need to check if it's valid, I wouldn't use a regex. If you need to extract potential IPs from blocks of other text, a regex would be useful.

        – JAL
        Oct 25 '10 at 7:28











      • It's a little bit of both, I need to use a regex for this, otherwise I need to add things to the framework and bladiblabla.

        – dutt
        Oct 25 '10 at 10:04

















      I thought about doing something like that, very neat with an explanation though :) Thanks.

      – dutt
      Oct 25 '10 at 4:23





      I thought about doing something like that, very neat with an explanation though :) Thanks.

      – dutt
      Oct 25 '10 at 4:23




      7




      7





      A good example of when not to use regexes.

      – Glenn Maynard
      Oct 25 '10 at 7:21





      A good example of when not to use regexes.

      – Glenn Maynard
      Oct 25 '10 at 7:21













      @Glenn Maynard if you already have the IP and need to check if it's valid, I wouldn't use a regex. If you need to extract potential IPs from blocks of other text, a regex would be useful.

      – JAL
      Oct 25 '10 at 7:28





      @Glenn Maynard if you already have the IP and need to check if it's valid, I wouldn't use a regex. If you need to extract potential IPs from blocks of other text, a regex would be useful.

      – JAL
      Oct 25 '10 at 7:28













      It's a little bit of both, I need to use a regex for this, otherwise I need to add things to the framework and bladiblabla.

      – dutt
      Oct 25 '10 at 10:04





      It's a little bit of both, I need to use a regex for this, otherwise I need to add things to the framework and bladiblabla.

      – dutt
      Oct 25 '10 at 10:04













      9














      No need for regular expressions here. Some background:



      >>> import socket
      >>> socket.inet_aton('255.255.255.255')
      'xffxffxffxff'
      >>> socket.inet_aton('255.255.255.256')
      Traceback (most recent call last):
      File "<input>", line 1, in <module>
      error: illegal IP address string passed to inet_aton
      >>> socket.inet_aton('my name is nobody')
      Traceback (most recent call last):
      File "<input>", line 1, in <module>
      error: illegal IP address string passed to inet_aton


      So:



      import socket

      def ip_address_is_valid(address):
      try: socket.inet_aton(address)
      except socket.error: return False
      else: return True


      Note that addresses like '127.1' could be acceptable on your machine (there are systems, including MS Windows and Linux, where missing octets are interpreted as zero, so '127.1' is equivalent to '127.0.0.1', and '10.1.4' is equivalent to '10.1.0.4'). Should you require that there are always 4 octets, change the last line from:



      else: return True


      into:



      else: return address.count('.') == 3





      share|improve this answer


























      • I thought that zero-filled was only the case with IPv6 addresses and the :: notation? It is frequently the case that when writing IP addresses with a CIDR mask that only the octets touched by the mask are written (10/8, 172.16/12, 192.168/16, 192.168.127/24), with a "zero-fill" on the remaining octets. But eliding zero-octets in the middle I've never seen with IPv4.

        – Vatine
        Oct 25 '10 at 8:17











      • @Vatine: I assume you: a) downvoted my answer because you thought I was stating something mistaken, while I was stating something you didn't know b) you've never pinged 127.1 yourself; please, do try it. Not only I am mistaken, but the creator of your IP stack is mistaken too. We apologize.

        – tzot
        Oct 25 '10 at 8:32











      • @ΤΖΩΤΖΙΟΥ: My ping expands 127.1 into 127.0.0.1 but it was concocted in the Dark Tower of Redmond where adherence to standards is sometimes a little casual so that proves nuffin :-)

        – John Machin
        Oct 25 '10 at 8:55











      • @John: of course it proves nuffin :) My ping —which was concocted in the Evil Forces of *nix— together with your ping just assert that 127.1 is acceptable

        – tzot
        Oct 25 '10 at 9:34













      • Just because the implied empty fields are accepted by some systems does not mean they are correct. That is like saying a single 32bit integer, expressed in decimal is valid, or that hex should be accepted (because some interfaces accept hex for the quads values.

        – benc
        Oct 25 '10 at 15:08
















      9














      No need for regular expressions here. Some background:



      >>> import socket
      >>> socket.inet_aton('255.255.255.255')
      'xffxffxffxff'
      >>> socket.inet_aton('255.255.255.256')
      Traceback (most recent call last):
      File "<input>", line 1, in <module>
      error: illegal IP address string passed to inet_aton
      >>> socket.inet_aton('my name is nobody')
      Traceback (most recent call last):
      File "<input>", line 1, in <module>
      error: illegal IP address string passed to inet_aton


      So:



      import socket

      def ip_address_is_valid(address):
      try: socket.inet_aton(address)
      except socket.error: return False
      else: return True


      Note that addresses like '127.1' could be acceptable on your machine (there are systems, including MS Windows and Linux, where missing octets are interpreted as zero, so '127.1' is equivalent to '127.0.0.1', and '10.1.4' is equivalent to '10.1.0.4'). Should you require that there are always 4 octets, change the last line from:



      else: return True


      into:



      else: return address.count('.') == 3





      share|improve this answer


























      • I thought that zero-filled was only the case with IPv6 addresses and the :: notation? It is frequently the case that when writing IP addresses with a CIDR mask that only the octets touched by the mask are written (10/8, 172.16/12, 192.168/16, 192.168.127/24), with a "zero-fill" on the remaining octets. But eliding zero-octets in the middle I've never seen with IPv4.

        – Vatine
        Oct 25 '10 at 8:17











      • @Vatine: I assume you: a) downvoted my answer because you thought I was stating something mistaken, while I was stating something you didn't know b) you've never pinged 127.1 yourself; please, do try it. Not only I am mistaken, but the creator of your IP stack is mistaken too. We apologize.

        – tzot
        Oct 25 '10 at 8:32











      • @ΤΖΩΤΖΙΟΥ: My ping expands 127.1 into 127.0.0.1 but it was concocted in the Dark Tower of Redmond where adherence to standards is sometimes a little casual so that proves nuffin :-)

        – John Machin
        Oct 25 '10 at 8:55











      • @John: of course it proves nuffin :) My ping —which was concocted in the Evil Forces of *nix— together with your ping just assert that 127.1 is acceptable

        – tzot
        Oct 25 '10 at 9:34













      • Just because the implied empty fields are accepted by some systems does not mean they are correct. That is like saying a single 32bit integer, expressed in decimal is valid, or that hex should be accepted (because some interfaces accept hex for the quads values.

        – benc
        Oct 25 '10 at 15:08














      9












      9








      9







      No need for regular expressions here. Some background:



      >>> import socket
      >>> socket.inet_aton('255.255.255.255')
      'xffxffxffxff'
      >>> socket.inet_aton('255.255.255.256')
      Traceback (most recent call last):
      File "<input>", line 1, in <module>
      error: illegal IP address string passed to inet_aton
      >>> socket.inet_aton('my name is nobody')
      Traceback (most recent call last):
      File "<input>", line 1, in <module>
      error: illegal IP address string passed to inet_aton


      So:



      import socket

      def ip_address_is_valid(address):
      try: socket.inet_aton(address)
      except socket.error: return False
      else: return True


      Note that addresses like '127.1' could be acceptable on your machine (there are systems, including MS Windows and Linux, where missing octets are interpreted as zero, so '127.1' is equivalent to '127.0.0.1', and '10.1.4' is equivalent to '10.1.0.4'). Should you require that there are always 4 octets, change the last line from:



      else: return True


      into:



      else: return address.count('.') == 3





      share|improve this answer















      No need for regular expressions here. Some background:



      >>> import socket
      >>> socket.inet_aton('255.255.255.255')
      'xffxffxffxff'
      >>> socket.inet_aton('255.255.255.256')
      Traceback (most recent call last):
      File "<input>", line 1, in <module>
      error: illegal IP address string passed to inet_aton
      >>> socket.inet_aton('my name is nobody')
      Traceback (most recent call last):
      File "<input>", line 1, in <module>
      error: illegal IP address string passed to inet_aton


      So:



      import socket

      def ip_address_is_valid(address):
      try: socket.inet_aton(address)
      except socket.error: return False
      else: return True


      Note that addresses like '127.1' could be acceptable on your machine (there are systems, including MS Windows and Linux, where missing octets are interpreted as zero, so '127.1' is equivalent to '127.0.0.1', and '10.1.4' is equivalent to '10.1.0.4'). Should you require that there are always 4 octets, change the last line from:



      else: return True


      into:



      else: return address.count('.') == 3






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Oct 25 '10 at 16:34

























      answered Oct 25 '10 at 5:55









      tzottzot

      65.1k21107176




      65.1k21107176













      • I thought that zero-filled was only the case with IPv6 addresses and the :: notation? It is frequently the case that when writing IP addresses with a CIDR mask that only the octets touched by the mask are written (10/8, 172.16/12, 192.168/16, 192.168.127/24), with a "zero-fill" on the remaining octets. But eliding zero-octets in the middle I've never seen with IPv4.

        – Vatine
        Oct 25 '10 at 8:17











      • @Vatine: I assume you: a) downvoted my answer because you thought I was stating something mistaken, while I was stating something you didn't know b) you've never pinged 127.1 yourself; please, do try it. Not only I am mistaken, but the creator of your IP stack is mistaken too. We apologize.

        – tzot
        Oct 25 '10 at 8:32











      • @ΤΖΩΤΖΙΟΥ: My ping expands 127.1 into 127.0.0.1 but it was concocted in the Dark Tower of Redmond where adherence to standards is sometimes a little casual so that proves nuffin :-)

        – John Machin
        Oct 25 '10 at 8:55











      • @John: of course it proves nuffin :) My ping —which was concocted in the Evil Forces of *nix— together with your ping just assert that 127.1 is acceptable

        – tzot
        Oct 25 '10 at 9:34













      • Just because the implied empty fields are accepted by some systems does not mean they are correct. That is like saying a single 32bit integer, expressed in decimal is valid, or that hex should be accepted (because some interfaces accept hex for the quads values.

        – benc
        Oct 25 '10 at 15:08



















      • I thought that zero-filled was only the case with IPv6 addresses and the :: notation? It is frequently the case that when writing IP addresses with a CIDR mask that only the octets touched by the mask are written (10/8, 172.16/12, 192.168/16, 192.168.127/24), with a "zero-fill" on the remaining octets. But eliding zero-octets in the middle I've never seen with IPv4.

        – Vatine
        Oct 25 '10 at 8:17











      • @Vatine: I assume you: a) downvoted my answer because you thought I was stating something mistaken, while I was stating something you didn't know b) you've never pinged 127.1 yourself; please, do try it. Not only I am mistaken, but the creator of your IP stack is mistaken too. We apologize.

        – tzot
        Oct 25 '10 at 8:32











      • @ΤΖΩΤΖΙΟΥ: My ping expands 127.1 into 127.0.0.1 but it was concocted in the Dark Tower of Redmond where adherence to standards is sometimes a little casual so that proves nuffin :-)

        – John Machin
        Oct 25 '10 at 8:55











      • @John: of course it proves nuffin :) My ping —which was concocted in the Evil Forces of *nix— together with your ping just assert that 127.1 is acceptable

        – tzot
        Oct 25 '10 at 9:34













      • Just because the implied empty fields are accepted by some systems does not mean they are correct. That is like saying a single 32bit integer, expressed in decimal is valid, or that hex should be accepted (because some interfaces accept hex for the quads values.

        – benc
        Oct 25 '10 at 15:08

















      I thought that zero-filled was only the case with IPv6 addresses and the :: notation? It is frequently the case that when writing IP addresses with a CIDR mask that only the octets touched by the mask are written (10/8, 172.16/12, 192.168/16, 192.168.127/24), with a "zero-fill" on the remaining octets. But eliding zero-octets in the middle I've never seen with IPv4.

      – Vatine
      Oct 25 '10 at 8:17





      I thought that zero-filled was only the case with IPv6 addresses and the :: notation? It is frequently the case that when writing IP addresses with a CIDR mask that only the octets touched by the mask are written (10/8, 172.16/12, 192.168/16, 192.168.127/24), with a "zero-fill" on the remaining octets. But eliding zero-octets in the middle I've never seen with IPv4.

      – Vatine
      Oct 25 '10 at 8:17













      @Vatine: I assume you: a) downvoted my answer because you thought I was stating something mistaken, while I was stating something you didn't know b) you've never pinged 127.1 yourself; please, do try it. Not only I am mistaken, but the creator of your IP stack is mistaken too. We apologize.

      – tzot
      Oct 25 '10 at 8:32





      @Vatine: I assume you: a) downvoted my answer because you thought I was stating something mistaken, while I was stating something you didn't know b) you've never pinged 127.1 yourself; please, do try it. Not only I am mistaken, but the creator of your IP stack is mistaken too. We apologize.

      – tzot
      Oct 25 '10 at 8:32













      @ΤΖΩΤΖΙΟΥ: My ping expands 127.1 into 127.0.0.1 but it was concocted in the Dark Tower of Redmond where adherence to standards is sometimes a little casual so that proves nuffin :-)

      – John Machin
      Oct 25 '10 at 8:55





      @ΤΖΩΤΖΙΟΥ: My ping expands 127.1 into 127.0.0.1 but it was concocted in the Dark Tower of Redmond where adherence to standards is sometimes a little casual so that proves nuffin :-)

      – John Machin
      Oct 25 '10 at 8:55













      @John: of course it proves nuffin :) My ping —which was concocted in the Evil Forces of *nix— together with your ping just assert that 127.1 is acceptable

      – tzot
      Oct 25 '10 at 9:34







      @John: of course it proves nuffin :) My ping —which was concocted in the Evil Forces of *nix— together with your ping just assert that 127.1 is acceptable

      – tzot
      Oct 25 '10 at 9:34















      Just because the implied empty fields are accepted by some systems does not mean they are correct. That is like saying a single 32bit integer, expressed in decimal is valid, or that hex should be accepted (because some interfaces accept hex for the quads values.

      – benc
      Oct 25 '10 at 15:08





      Just because the implied empty fields are accepted by some systems does not mean they are correct. That is like saying a single 32bit integer, expressed in decimal is valid, or that hex should be accepted (because some interfaces accept hex for the quads values.

      – benc
      Oct 25 '10 at 15:08











      6














      You can check a 4-octet IP address easily without regexes at all. Here's a tested working method:



      >>> def valid_ip(ip):
      ... parts = ip.split('.')
      ... return (
      ... len(parts) == 4
      ... and all(part.isdigit() for part in parts)
      ... and all(0 <= int(part) <= 255 for part in parts)
      ... )
      ...
      >>> valid_ip('1.2.3.4')
      True
      >>> valid_ip('1.2.3.4.5')
      False
      >>> valid_ip('1.2. 3 .4.5')
      False
      >>> valid_ip('1.256.3.4.5')
      False
      >>> valid_ip('1.B.3.4')
      False
      >>>





      share|improve this answer




























        6














        You can check a 4-octet IP address easily without regexes at all. Here's a tested working method:



        >>> def valid_ip(ip):
        ... parts = ip.split('.')
        ... return (
        ... len(parts) == 4
        ... and all(part.isdigit() for part in parts)
        ... and all(0 <= int(part) <= 255 for part in parts)
        ... )
        ...
        >>> valid_ip('1.2.3.4')
        True
        >>> valid_ip('1.2.3.4.5')
        False
        >>> valid_ip('1.2. 3 .4.5')
        False
        >>> valid_ip('1.256.3.4.5')
        False
        >>> valid_ip('1.B.3.4')
        False
        >>>





        share|improve this answer


























          6












          6








          6







          You can check a 4-octet IP address easily without regexes at all. Here's a tested working method:



          >>> def valid_ip(ip):
          ... parts = ip.split('.')
          ... return (
          ... len(parts) == 4
          ... and all(part.isdigit() for part in parts)
          ... and all(0 <= int(part) <= 255 for part in parts)
          ... )
          ...
          >>> valid_ip('1.2.3.4')
          True
          >>> valid_ip('1.2.3.4.5')
          False
          >>> valid_ip('1.2. 3 .4.5')
          False
          >>> valid_ip('1.256.3.4.5')
          False
          >>> valid_ip('1.B.3.4')
          False
          >>>





          share|improve this answer













          You can check a 4-octet IP address easily without regexes at all. Here's a tested working method:



          >>> def valid_ip(ip):
          ... parts = ip.split('.')
          ... return (
          ... len(parts) == 4
          ... and all(part.isdigit() for part in parts)
          ... and all(0 <= int(part) <= 255 for part in parts)
          ... )
          ...
          >>> valid_ip('1.2.3.4')
          True
          >>> valid_ip('1.2.3.4.5')
          False
          >>> valid_ip('1.2. 3 .4.5')
          False
          >>> valid_ip('1.256.3.4.5')
          False
          >>> valid_ip('1.B.3.4')
          False
          >>>






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Oct 25 '10 at 5:47









          John MachinJohn Machin

          65.6k7100162




          65.6k7100162























              3














              Regex is for pattern matching, but to check for a valid IP, you need to check for the range (i.e. 0 <= n <= 255).



              You may use regex to check for range, but that'll be a bit overkill. I think you're better off checking for basic patter and then check for the range for each number.



              For example, use the following pattern to match an IP:



              ([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3})


              Then check whether each number is within range.






              share|improve this answer
























              • Or more compact: (([0-9]{1,3}.){3}[0-9]{1,3})

                – whirlwin
                Feb 15 '11 at 19:38
















              3














              Regex is for pattern matching, but to check for a valid IP, you need to check for the range (i.e. 0 <= n <= 255).



              You may use regex to check for range, but that'll be a bit overkill. I think you're better off checking for basic patter and then check for the range for each number.



              For example, use the following pattern to match an IP:



              ([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3})


              Then check whether each number is within range.






              share|improve this answer
























              • Or more compact: (([0-9]{1,3}.){3}[0-9]{1,3})

                – whirlwin
                Feb 15 '11 at 19:38














              3












              3








              3







              Regex is for pattern matching, but to check for a valid IP, you need to check for the range (i.e. 0 <= n <= 255).



              You may use regex to check for range, but that'll be a bit overkill. I think you're better off checking for basic patter and then check for the range for each number.



              For example, use the following pattern to match an IP:



              ([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3})


              Then check whether each number is within range.






              share|improve this answer













              Regex is for pattern matching, but to check for a valid IP, you need to check for the range (i.e. 0 <= n <= 255).



              You may use regex to check for range, but that'll be a bit overkill. I think you're better off checking for basic patter and then check for the range for each number.



              For example, use the following pattern to match an IP:



              ([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3})


              Then check whether each number is within range.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Oct 25 '10 at 4:20









              William NiuWilliam Niu

              14k74691




              14k74691













              • Or more compact: (([0-9]{1,3}.){3}[0-9]{1,3})

                – whirlwin
                Feb 15 '11 at 19:38



















              • Or more compact: (([0-9]{1,3}.){3}[0-9]{1,3})

                – whirlwin
                Feb 15 '11 at 19:38

















              Or more compact: (([0-9]{1,3}.){3}[0-9]{1,3})

              – whirlwin
              Feb 15 '11 at 19:38





              Or more compact: (([0-9]{1,3}.){3}[0-9]{1,3})

              – whirlwin
              Feb 15 '11 at 19:38











              3














              The following supports IPv4, IPv6 as well as Python 2.7 & 3.3



              import socket


              def is_valid_ipv4(ip_str):
              """
              Check the validity of an IPv4 address
              """
              try:
              socket.inet_pton(socket.AF_INET, ip_str)
              except AttributeError:
              try:
              socket.inet_aton(ip_str)
              except socket.error:
              return False
              return ip_str.count('.') == 3
              except socket.error:
              return False
              return True


              def is_valid_ipv6(ip_str):
              """
              Check the validity of an IPv6 address
              """
              try:
              socket.inet_pton(socket.AF_INET6, ip_str)
              except socket.error:
              return False
              return True


              def is_valid_ip(ip_str):
              """
              Check the validity of an IP address
              """
              return is_valid_ipv4(ip_str) or is_valid_ipv6(ip_str)





              share|improve this answer
























              • this is the best answer of all, but for windows users win_inet_pton must be installed, and the import statement should be changed to: try: import win_inet_pton except ImportError: pass import socket

                – StefanNch
                Nov 2 '14 at 10:45
















              3














              The following supports IPv4, IPv6 as well as Python 2.7 & 3.3



              import socket


              def is_valid_ipv4(ip_str):
              """
              Check the validity of an IPv4 address
              """
              try:
              socket.inet_pton(socket.AF_INET, ip_str)
              except AttributeError:
              try:
              socket.inet_aton(ip_str)
              except socket.error:
              return False
              return ip_str.count('.') == 3
              except socket.error:
              return False
              return True


              def is_valid_ipv6(ip_str):
              """
              Check the validity of an IPv6 address
              """
              try:
              socket.inet_pton(socket.AF_INET6, ip_str)
              except socket.error:
              return False
              return True


              def is_valid_ip(ip_str):
              """
              Check the validity of an IP address
              """
              return is_valid_ipv4(ip_str) or is_valid_ipv6(ip_str)





              share|improve this answer
























              • this is the best answer of all, but for windows users win_inet_pton must be installed, and the import statement should be changed to: try: import win_inet_pton except ImportError: pass import socket

                – StefanNch
                Nov 2 '14 at 10:45














              3












              3








              3







              The following supports IPv4, IPv6 as well as Python 2.7 & 3.3



              import socket


              def is_valid_ipv4(ip_str):
              """
              Check the validity of an IPv4 address
              """
              try:
              socket.inet_pton(socket.AF_INET, ip_str)
              except AttributeError:
              try:
              socket.inet_aton(ip_str)
              except socket.error:
              return False
              return ip_str.count('.') == 3
              except socket.error:
              return False
              return True


              def is_valid_ipv6(ip_str):
              """
              Check the validity of an IPv6 address
              """
              try:
              socket.inet_pton(socket.AF_INET6, ip_str)
              except socket.error:
              return False
              return True


              def is_valid_ip(ip_str):
              """
              Check the validity of an IP address
              """
              return is_valid_ipv4(ip_str) or is_valid_ipv6(ip_str)





              share|improve this answer













              The following supports IPv4, IPv6 as well as Python 2.7 & 3.3



              import socket


              def is_valid_ipv4(ip_str):
              """
              Check the validity of an IPv4 address
              """
              try:
              socket.inet_pton(socket.AF_INET, ip_str)
              except AttributeError:
              try:
              socket.inet_aton(ip_str)
              except socket.error:
              return False
              return ip_str.count('.') == 3
              except socket.error:
              return False
              return True


              def is_valid_ipv6(ip_str):
              """
              Check the validity of an IPv6 address
              """
              try:
              socket.inet_pton(socket.AF_INET6, ip_str)
              except socket.error:
              return False
              return True


              def is_valid_ip(ip_str):
              """
              Check the validity of an IP address
              """
              return is_valid_ipv4(ip_str) or is_valid_ipv6(ip_str)






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered May 6 '14 at 18:18









              un33kun33k

              9,285125258




              9,285125258













              • this is the best answer of all, but for windows users win_inet_pton must be installed, and the import statement should be changed to: try: import win_inet_pton except ImportError: pass import socket

                – StefanNch
                Nov 2 '14 at 10:45



















              • this is the best answer of all, but for windows users win_inet_pton must be installed, and the import statement should be changed to: try: import win_inet_pton except ImportError: pass import socket

                – StefanNch
                Nov 2 '14 at 10:45

















              this is the best answer of all, but for windows users win_inet_pton must be installed, and the import statement should be changed to: try: import win_inet_pton except ImportError: pass import socket

              – StefanNch
              Nov 2 '14 at 10:45





              this is the best answer of all, but for windows users win_inet_pton must be installed, and the import statement should be changed to: try: import win_inet_pton except ImportError: pass import socket

              – StefanNch
              Nov 2 '14 at 10:45











              0














              IP addresses can also be checked with split as follows,



              all(map((lambda x: 0<=x<=255),map(int,ip.split('.')))) and len(ip.split("."))==4


              For me thats a little bit more readable than regex.






              share|improve this answer
























              • huh, kind of a neat solution too. thanks :)

                – dutt
                Oct 25 '10 at 4:54











              • -2 FAIL on '1. 2 .3.4' and FAIL on '1.B.2.3' @dutt: be suspicious of anything with 2 * map() and excess parentheses and test before use.

                – John Machin
                Oct 25 '10 at 5:46











              • The "readable" expression can be reduced to the equivalent all(map(lambda x: 0<=int(x)<=255,ip.split('.'))) and len(ip.split("."))==4 by removing a map() call and the redundant parentheses around the lambda expression (but still fails, of course)

                – John Machin
                Oct 25 '10 at 5:57











              • @John Machin, I accept that I didn't test for the possibility of spaces (my bad). But '1.B.2.3' test doesn't fail. I get a value error. ValueError: invalid literal for int() with base 10: 'B'

                – Sujoy
                Oct 25 '10 at 15:10











              • crashes instead of returning False. That's not a fail???

                – John Machin
                Oct 25 '10 at 20:40
















              0














              IP addresses can also be checked with split as follows,



              all(map((lambda x: 0<=x<=255),map(int,ip.split('.')))) and len(ip.split("."))==4


              For me thats a little bit more readable than regex.






              share|improve this answer
























              • huh, kind of a neat solution too. thanks :)

                – dutt
                Oct 25 '10 at 4:54











              • -2 FAIL on '1. 2 .3.4' and FAIL on '1.B.2.3' @dutt: be suspicious of anything with 2 * map() and excess parentheses and test before use.

                – John Machin
                Oct 25 '10 at 5:46











              • The "readable" expression can be reduced to the equivalent all(map(lambda x: 0<=int(x)<=255,ip.split('.'))) and len(ip.split("."))==4 by removing a map() call and the redundant parentheses around the lambda expression (but still fails, of course)

                – John Machin
                Oct 25 '10 at 5:57











              • @John Machin, I accept that I didn't test for the possibility of spaces (my bad). But '1.B.2.3' test doesn't fail. I get a value error. ValueError: invalid literal for int() with base 10: 'B'

                – Sujoy
                Oct 25 '10 at 15:10











              • crashes instead of returning False. That's not a fail???

                – John Machin
                Oct 25 '10 at 20:40














              0












              0








              0







              IP addresses can also be checked with split as follows,



              all(map((lambda x: 0<=x<=255),map(int,ip.split('.')))) and len(ip.split("."))==4


              For me thats a little bit more readable than regex.






              share|improve this answer













              IP addresses can also be checked with split as follows,



              all(map((lambda x: 0<=x<=255),map(int,ip.split('.')))) and len(ip.split("."))==4


              For me thats a little bit more readable than regex.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Oct 25 '10 at 4:46









              SujoySujoy

              5,41622436




              5,41622436













              • huh, kind of a neat solution too. thanks :)

                – dutt
                Oct 25 '10 at 4:54











              • -2 FAIL on '1. 2 .3.4' and FAIL on '1.B.2.3' @dutt: be suspicious of anything with 2 * map() and excess parentheses and test before use.

                – John Machin
                Oct 25 '10 at 5:46











              • The "readable" expression can be reduced to the equivalent all(map(lambda x: 0<=int(x)<=255,ip.split('.'))) and len(ip.split("."))==4 by removing a map() call and the redundant parentheses around the lambda expression (but still fails, of course)

                – John Machin
                Oct 25 '10 at 5:57











              • @John Machin, I accept that I didn't test for the possibility of spaces (my bad). But '1.B.2.3' test doesn't fail. I get a value error. ValueError: invalid literal for int() with base 10: 'B'

                – Sujoy
                Oct 25 '10 at 15:10











              • crashes instead of returning False. That's not a fail???

                – John Machin
                Oct 25 '10 at 20:40



















              • huh, kind of a neat solution too. thanks :)

                – dutt
                Oct 25 '10 at 4:54











              • -2 FAIL on '1. 2 .3.4' and FAIL on '1.B.2.3' @dutt: be suspicious of anything with 2 * map() and excess parentheses and test before use.

                – John Machin
                Oct 25 '10 at 5:46











              • The "readable" expression can be reduced to the equivalent all(map(lambda x: 0<=int(x)<=255,ip.split('.'))) and len(ip.split("."))==4 by removing a map() call and the redundant parentheses around the lambda expression (but still fails, of course)

                – John Machin
                Oct 25 '10 at 5:57











              • @John Machin, I accept that I didn't test for the possibility of spaces (my bad). But '1.B.2.3' test doesn't fail. I get a value error. ValueError: invalid literal for int() with base 10: 'B'

                – Sujoy
                Oct 25 '10 at 15:10











              • crashes instead of returning False. That's not a fail???

                – John Machin
                Oct 25 '10 at 20:40

















              huh, kind of a neat solution too. thanks :)

              – dutt
              Oct 25 '10 at 4:54





              huh, kind of a neat solution too. thanks :)

              – dutt
              Oct 25 '10 at 4:54













              -2 FAIL on '1. 2 .3.4' and FAIL on '1.B.2.3' @dutt: be suspicious of anything with 2 * map() and excess parentheses and test before use.

              – John Machin
              Oct 25 '10 at 5:46





              -2 FAIL on '1. 2 .3.4' and FAIL on '1.B.2.3' @dutt: be suspicious of anything with 2 * map() and excess parentheses and test before use.

              – John Machin
              Oct 25 '10 at 5:46













              The "readable" expression can be reduced to the equivalent all(map(lambda x: 0<=int(x)<=255,ip.split('.'))) and len(ip.split("."))==4 by removing a map() call and the redundant parentheses around the lambda expression (but still fails, of course)

              – John Machin
              Oct 25 '10 at 5:57





              The "readable" expression can be reduced to the equivalent all(map(lambda x: 0<=int(x)<=255,ip.split('.'))) and len(ip.split("."))==4 by removing a map() call and the redundant parentheses around the lambda expression (but still fails, of course)

              – John Machin
              Oct 25 '10 at 5:57













              @John Machin, I accept that I didn't test for the possibility of spaces (my bad). But '1.B.2.3' test doesn't fail. I get a value error. ValueError: invalid literal for int() with base 10: 'B'

              – Sujoy
              Oct 25 '10 at 15:10





              @John Machin, I accept that I didn't test for the possibility of spaces (my bad). But '1.B.2.3' test doesn't fail. I get a value error. ValueError: invalid literal for int() with base 10: 'B'

              – Sujoy
              Oct 25 '10 at 15:10













              crashes instead of returning False. That's not a fail???

              – John Machin
              Oct 25 '10 at 20:40





              crashes instead of returning False. That's not a fail???

              – John Machin
              Oct 25 '10 at 20:40











              0














              I think people are taking this too far I suggest you first do this:
              ips = re.findall('(?:[d]{1,3}).(?:[d]{1,3}).(?:[d]{1,3}).(?:[d]{1,3})', page)
              then split the 4 numbers where there is a '.' and check and see if they are smaller than 256






              share|improve this answer




























                0














                I think people are taking this too far I suggest you first do this:
                ips = re.findall('(?:[d]{1,3}).(?:[d]{1,3}).(?:[d]{1,3}).(?:[d]{1,3})', page)
                then split the 4 numbers where there is a '.' and check and see if they are smaller than 256






                share|improve this answer


























                  0












                  0








                  0







                  I think people are taking this too far I suggest you first do this:
                  ips = re.findall('(?:[d]{1,3}).(?:[d]{1,3}).(?:[d]{1,3}).(?:[d]{1,3})', page)
                  then split the 4 numbers where there is a '.' and check and see if they are smaller than 256






                  share|improve this answer













                  I think people are taking this too far I suggest you first do this:
                  ips = re.findall('(?:[d]{1,3}).(?:[d]{1,3}).(?:[d]{1,3}).(?:[d]{1,3})', page)
                  then split the 4 numbers where there is a '.' and check and see if they are smaller than 256







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered May 19 '11 at 20:45









                  MaxMax

                  1,42532342




                  1,42532342























                      0














                      You need this-



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


                      Regular expression visualization



                      Debuggex Demo






                      share|improve this answer


























                      • So is 219.1.1.1 a valid or an invalid IP address?

                        – tzot
                        Oct 2 '14 at 23:46











                      • why not, can u explain?

                        – Rajesh Paul
                        Oct 4 '14 at 6:14











                      • Let me rephrase: does 219.1.1.1 (a valid IP address) pass your regex test?

                        – tzot
                        Oct 4 '14 at 18:49











                      • Thanx @tzot, for this correction.

                        – Rajesh Paul
                        Oct 5 '14 at 4:45
















                      0














                      You need this-



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


                      Regular expression visualization



                      Debuggex Demo






                      share|improve this answer


























                      • So is 219.1.1.1 a valid or an invalid IP address?

                        – tzot
                        Oct 2 '14 at 23:46











                      • why not, can u explain?

                        – Rajesh Paul
                        Oct 4 '14 at 6:14











                      • Let me rephrase: does 219.1.1.1 (a valid IP address) pass your regex test?

                        – tzot
                        Oct 4 '14 at 18:49











                      • Thanx @tzot, for this correction.

                        – Rajesh Paul
                        Oct 5 '14 at 4:45














                      0












                      0








                      0







                      You need this-



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


                      Regular expression visualization



                      Debuggex Demo






                      share|improve this answer















                      You need this-



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


                      Regular expression visualization



                      Debuggex Demo







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Oct 5 '14 at 4:44

























                      answered Dec 21 '13 at 5:27









                      Rajesh PaulRajesh Paul

                      3,85562642




                      3,85562642













                      • So is 219.1.1.1 a valid or an invalid IP address?

                        – tzot
                        Oct 2 '14 at 23:46











                      • why not, can u explain?

                        – Rajesh Paul
                        Oct 4 '14 at 6:14











                      • Let me rephrase: does 219.1.1.1 (a valid IP address) pass your regex test?

                        – tzot
                        Oct 4 '14 at 18:49











                      • Thanx @tzot, for this correction.

                        – Rajesh Paul
                        Oct 5 '14 at 4:45



















                      • So is 219.1.1.1 a valid or an invalid IP address?

                        – tzot
                        Oct 2 '14 at 23:46











                      • why not, can u explain?

                        – Rajesh Paul
                        Oct 4 '14 at 6:14











                      • Let me rephrase: does 219.1.1.1 (a valid IP address) pass your regex test?

                        – tzot
                        Oct 4 '14 at 18:49











                      • Thanx @tzot, for this correction.

                        – Rajesh Paul
                        Oct 5 '14 at 4:45

















                      So is 219.1.1.1 a valid or an invalid IP address?

                      – tzot
                      Oct 2 '14 at 23:46





                      So is 219.1.1.1 a valid or an invalid IP address?

                      – tzot
                      Oct 2 '14 at 23:46













                      why not, can u explain?

                      – Rajesh Paul
                      Oct 4 '14 at 6:14





                      why not, can u explain?

                      – Rajesh Paul
                      Oct 4 '14 at 6:14













                      Let me rephrase: does 219.1.1.1 (a valid IP address) pass your regex test?

                      – tzot
                      Oct 4 '14 at 18:49





                      Let me rephrase: does 219.1.1.1 (a valid IP address) pass your regex test?

                      – tzot
                      Oct 4 '14 at 18:49













                      Thanx @tzot, for this correction.

                      – Rajesh Paul
                      Oct 5 '14 at 4:45





                      Thanx @tzot, for this correction.

                      – Rajesh Paul
                      Oct 5 '14 at 4:45


















                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4011855%2fregexp-to-check-if-an-ip-is-valid%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Monofisismo

                      Angular Downloading a file using contenturl with Basic Authentication

                      Olmecas