Validate IP4 address












7












$begingroup$


Validate IP Address



I got this problem during an interview. And would like to get some code review. I also wrote several tests with the expected output, and they all passed as expected.




Validate an IP address (IPv4). An address is valid if and only if it
is in the form "X.X.X.X", where each X is a number from 0 to 255.



For example, "12.34.5.6", "0.23.25.0", and "255.255.255.255" are valid
IP addresses, while "12.34.56.oops", "1.2.3.4.5", and
"123.235.153.425" are invalid IP addresses.




Examples:

"""

ip = '192.168.0.1'
output: true

ip = '0.0.0.0'
output: true

ip = '123.24.59.99'
output: true

ip = '192.168.123.456'
output: false
"""

def validateIP(ip):
#split them by '.' , and store them in an array
#check the array if the length is 4 length
arr = ip.split('.')
if len(arr) != 4:
return False
#0 check for special edge cases when non-digit
#1. check if they are digit,
#2. check if check the integer is between 0 and 255

for part in arr:
if len(part) > 1:
if part[0] == '0':
return False
if not part.isdigit():
return False
digit = int(part)
if digit < 0 or digit > 255:
return False
return True

#case#0

ip0="08.0.0.0" # False
test0= validateIP(ip0)
print(test0)

#case#1
ip1 = "192.168.0.1"
test1 = validateIP(ip1)
print(test1)

#case#2
ip2 = '0.0.0.0'
test2 = validateIP(ip2)
print(test2)

#case#3
ip3 = '123.24.59.99'
test3 = validateIP(ip3)
print(test3)

#case#4
ip4 = '192.168.123.456'
test4 = validateIP(ip4)
print(test4)

#case5
ip5 = "255.255.255.255"
test5 = validateIP(ip5)
print(test5)









share|improve this question











$endgroup$

















    7












    $begingroup$


    Validate IP Address



    I got this problem during an interview. And would like to get some code review. I also wrote several tests with the expected output, and they all passed as expected.




    Validate an IP address (IPv4). An address is valid if and only if it
    is in the form "X.X.X.X", where each X is a number from 0 to 255.



    For example, "12.34.5.6", "0.23.25.0", and "255.255.255.255" are valid
    IP addresses, while "12.34.56.oops", "1.2.3.4.5", and
    "123.235.153.425" are invalid IP addresses.




    Examples:

    """

    ip = '192.168.0.1'
    output: true

    ip = '0.0.0.0'
    output: true

    ip = '123.24.59.99'
    output: true

    ip = '192.168.123.456'
    output: false
    """

    def validateIP(ip):
    #split them by '.' , and store them in an array
    #check the array if the length is 4 length
    arr = ip.split('.')
    if len(arr) != 4:
    return False
    #0 check for special edge cases when non-digit
    #1. check if they are digit,
    #2. check if check the integer is between 0 and 255

    for part in arr:
    if len(part) > 1:
    if part[0] == '0':
    return False
    if not part.isdigit():
    return False
    digit = int(part)
    if digit < 0 or digit > 255:
    return False
    return True

    #case#0

    ip0="08.0.0.0" # False
    test0= validateIP(ip0)
    print(test0)

    #case#1
    ip1 = "192.168.0.1"
    test1 = validateIP(ip1)
    print(test1)

    #case#2
    ip2 = '0.0.0.0'
    test2 = validateIP(ip2)
    print(test2)

    #case#3
    ip3 = '123.24.59.99'
    test3 = validateIP(ip3)
    print(test3)

    #case#4
    ip4 = '192.168.123.456'
    test4 = validateIP(ip4)
    print(test4)

    #case5
    ip5 = "255.255.255.255"
    test5 = validateIP(ip5)
    print(test5)









    share|improve this question











    $endgroup$















      7












      7








      7


      1



      $begingroup$


      Validate IP Address



      I got this problem during an interview. And would like to get some code review. I also wrote several tests with the expected output, and they all passed as expected.




      Validate an IP address (IPv4). An address is valid if and only if it
      is in the form "X.X.X.X", where each X is a number from 0 to 255.



      For example, "12.34.5.6", "0.23.25.0", and "255.255.255.255" are valid
      IP addresses, while "12.34.56.oops", "1.2.3.4.5", and
      "123.235.153.425" are invalid IP addresses.




      Examples:

      """

      ip = '192.168.0.1'
      output: true

      ip = '0.0.0.0'
      output: true

      ip = '123.24.59.99'
      output: true

      ip = '192.168.123.456'
      output: false
      """

      def validateIP(ip):
      #split them by '.' , and store them in an array
      #check the array if the length is 4 length
      arr = ip.split('.')
      if len(arr) != 4:
      return False
      #0 check for special edge cases when non-digit
      #1. check if they are digit,
      #2. check if check the integer is between 0 and 255

      for part in arr:
      if len(part) > 1:
      if part[0] == '0':
      return False
      if not part.isdigit():
      return False
      digit = int(part)
      if digit < 0 or digit > 255:
      return False
      return True

      #case#0

      ip0="08.0.0.0" # False
      test0= validateIP(ip0)
      print(test0)

      #case#1
      ip1 = "192.168.0.1"
      test1 = validateIP(ip1)
      print(test1)

      #case#2
      ip2 = '0.0.0.0'
      test2 = validateIP(ip2)
      print(test2)

      #case#3
      ip3 = '123.24.59.99'
      test3 = validateIP(ip3)
      print(test3)

      #case#4
      ip4 = '192.168.123.456'
      test4 = validateIP(ip4)
      print(test4)

      #case5
      ip5 = "255.255.255.255"
      test5 = validateIP(ip5)
      print(test5)









      share|improve this question











      $endgroup$




      Validate IP Address



      I got this problem during an interview. And would like to get some code review. I also wrote several tests with the expected output, and they all passed as expected.




      Validate an IP address (IPv4). An address is valid if and only if it
      is in the form "X.X.X.X", where each X is a number from 0 to 255.



      For example, "12.34.5.6", "0.23.25.0", and "255.255.255.255" are valid
      IP addresses, while "12.34.56.oops", "1.2.3.4.5", and
      "123.235.153.425" are invalid IP addresses.




      Examples:

      """

      ip = '192.168.0.1'
      output: true

      ip = '0.0.0.0'
      output: true

      ip = '123.24.59.99'
      output: true

      ip = '192.168.123.456'
      output: false
      """

      def validateIP(ip):
      #split them by '.' , and store them in an array
      #check the array if the length is 4 length
      arr = ip.split('.')
      if len(arr) != 4:
      return False
      #0 check for special edge cases when non-digit
      #1. check if they are digit,
      #2. check if check the integer is between 0 and 255

      for part in arr:
      if len(part) > 1:
      if part[0] == '0':
      return False
      if not part.isdigit():
      return False
      digit = int(part)
      if digit < 0 or digit > 255:
      return False
      return True

      #case#0

      ip0="08.0.0.0" # False
      test0= validateIP(ip0)
      print(test0)

      #case#1
      ip1 = "192.168.0.1"
      test1 = validateIP(ip1)
      print(test1)

      #case#2
      ip2 = '0.0.0.0'
      test2 = validateIP(ip2)
      print(test2)

      #case#3
      ip3 = '123.24.59.99'
      test3 = validateIP(ip3)
      print(test3)

      #case#4
      ip4 = '192.168.123.456'
      test4 = validateIP(ip4)
      print(test4)

      #case5
      ip5 = "255.255.255.255"
      test5 = validateIP(ip5)
      print(test5)






      python interview-questions validation ip-address






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 2 hours ago









      200_success

      130k17155419




      130k17155419










      asked 9 hours ago









      NinjaGNinjaG

      893632




      893632






















          2 Answers
          2






          active

          oldest

          votes


















          8












          $begingroup$


          def validateIP(ip):



          I would expect a name starting is (a useful hint that it returns a Boolean rather than some more complex validation data structure) and explicitly mentioning IP v4 (since the current name is misleading). E.g. is_valid_IPv4_address.






            #split them by '.' , and store them in an array
          #check the array if the length is 4 length
          arr = ip.split('.')
          if len(arr) != 4:
          return False



          The comments don't tell me anything which the code doesn't already. In general, good comments explain why, not what.






            #0 check for special edge cases when non-digit
          #1. check if they are digit,
          #2. check if check the integer is between 0 and 255

          for part in arr:
          .. various conditions which return False
          return True



          IMO it would be more Pythonic to use all: I would boil the whole function down to



              parts = ip.split('.')
          return len(parts) == 4 and all(is_valid_IPv4_address_part(part) for part in parts)





              if len(part) > 1:
          if part[0] == '0':
          return False



          This isn't in the spec. It's a reasonable constraint, but you should check with the person who gave you the spec before writing the code, or at least put in a comment saying that you're making an assumption about the true intentions of the specifier.






              if not part.isdigit():
          return False



          This is buggy. (Before testing I thought there was an issue which should be bounced back to the specifier. Upon testing, I found that some of my test cases caused validateIP to throw an exception).



          What is the expected output for these test cases?



          ¹.¹.¹.¹
          ١.١.١.١
          𝟣.𝟣.𝟣.𝟣
          ①.①.①.①





          share|improve this answer









          $endgroup$





















            7












            $begingroup$



            1. A doc string reads nicer then # blockcomments



              Consider making a doc string of that function, so you can do help(validate_ip) and it will print the doc string in the interpreter.




            2. Adhere to PEP8



              Functions and variables should be snake_case ie def validate_ip(ip):



            3. You could use the all keyword to check if each part is correct; this will return False for the first failure.



            4. Make actual tests that ensure validity



              Instead of printing tests, make actual tests either with assert or the modules doctest or unittest.




            5. There is a module that does this for you



              Python is often described as "batteries included", and here you could use the ipaddress module, which will validate an IP when you create the IPv4Adress object.




            Reworked code



            import doctest

            def validate_ip(ip):
            """
            Checks if the ip address is valid
            args:
            ip (str): The IP address
            ret:
            A boolean: True for a a valid IP

            >>> validate_ip('08.0.0.0')
            False

            >>> validate_ip('192.169.0.1')
            True

            >>> validate_ip('0.0.0.0')
            True

            >>> validate_ip('192.168.123.456')
            False

            >>> validate_ip('oooh.0.0.1')
            False
            """
            ranges = ip.split('.')
            return len(ranges) == 4
            and all(
            r.isdigit() and # Check for digits
            int(r) in range(0, 256) and # Check in range of 0-255
            (r[0] != "0" or len(r) == 1) # Check for leading zero's
            for r in ranges
            )

            if __name__ == '__main__':
            doctest.testmod()


            ipaddress module



            from ipaddress import IPv4Address

            def is_valid_ip(ip):
            try:
            IPv4Address(ip)
            return True
            except ValueError:
            return False





            share|improve this answer











            $endgroup$













            • $begingroup$
              As a bonus, docstrings are picked up by Python's built-in help mechanisms.
              $endgroup$
              – Alex
              6 hours ago










            • $begingroup$
              @Alex I did mention help
              $endgroup$
              – Ludisposed
              6 hours ago










            • $begingroup$
              Sorry, must have skipped over this.
              $endgroup$
              – Alex
              6 hours ago











            Your Answer





            StackExchange.ifUsing("editor", function () {
            return StackExchange.using("mathjaxEditing", function () {
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
            });
            });
            }, "mathjax-editing");

            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: "196"
            };
            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: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            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%2fcodereview.stackexchange.com%2fquestions%2f216311%2fvalidate-ip4-address%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            8












            $begingroup$


            def validateIP(ip):



            I would expect a name starting is (a useful hint that it returns a Boolean rather than some more complex validation data structure) and explicitly mentioning IP v4 (since the current name is misleading). E.g. is_valid_IPv4_address.






              #split them by '.' , and store them in an array
            #check the array if the length is 4 length
            arr = ip.split('.')
            if len(arr) != 4:
            return False



            The comments don't tell me anything which the code doesn't already. In general, good comments explain why, not what.






              #0 check for special edge cases when non-digit
            #1. check if they are digit,
            #2. check if check the integer is between 0 and 255

            for part in arr:
            .. various conditions which return False
            return True



            IMO it would be more Pythonic to use all: I would boil the whole function down to



                parts = ip.split('.')
            return len(parts) == 4 and all(is_valid_IPv4_address_part(part) for part in parts)





                if len(part) > 1:
            if part[0] == '0':
            return False



            This isn't in the spec. It's a reasonable constraint, but you should check with the person who gave you the spec before writing the code, or at least put in a comment saying that you're making an assumption about the true intentions of the specifier.






                if not part.isdigit():
            return False



            This is buggy. (Before testing I thought there was an issue which should be bounced back to the specifier. Upon testing, I found that some of my test cases caused validateIP to throw an exception).



            What is the expected output for these test cases?



            ¹.¹.¹.¹
            ١.١.١.١
            𝟣.𝟣.𝟣.𝟣
            ①.①.①.①





            share|improve this answer









            $endgroup$


















              8












              $begingroup$


              def validateIP(ip):



              I would expect a name starting is (a useful hint that it returns a Boolean rather than some more complex validation data structure) and explicitly mentioning IP v4 (since the current name is misleading). E.g. is_valid_IPv4_address.






                #split them by '.' , and store them in an array
              #check the array if the length is 4 length
              arr = ip.split('.')
              if len(arr) != 4:
              return False



              The comments don't tell me anything which the code doesn't already. In general, good comments explain why, not what.






                #0 check for special edge cases when non-digit
              #1. check if they are digit,
              #2. check if check the integer is between 0 and 255

              for part in arr:
              .. various conditions which return False
              return True



              IMO it would be more Pythonic to use all: I would boil the whole function down to



                  parts = ip.split('.')
              return len(parts) == 4 and all(is_valid_IPv4_address_part(part) for part in parts)





                  if len(part) > 1:
              if part[0] == '0':
              return False



              This isn't in the spec. It's a reasonable constraint, but you should check with the person who gave you the spec before writing the code, or at least put in a comment saying that you're making an assumption about the true intentions of the specifier.






                  if not part.isdigit():
              return False



              This is buggy. (Before testing I thought there was an issue which should be bounced back to the specifier. Upon testing, I found that some of my test cases caused validateIP to throw an exception).



              What is the expected output for these test cases?



              ¹.¹.¹.¹
              ١.١.١.١
              𝟣.𝟣.𝟣.𝟣
              ①.①.①.①





              share|improve this answer









              $endgroup$
















                8












                8








                8





                $begingroup$


                def validateIP(ip):



                I would expect a name starting is (a useful hint that it returns a Boolean rather than some more complex validation data structure) and explicitly mentioning IP v4 (since the current name is misleading). E.g. is_valid_IPv4_address.






                  #split them by '.' , and store them in an array
                #check the array if the length is 4 length
                arr = ip.split('.')
                if len(arr) != 4:
                return False



                The comments don't tell me anything which the code doesn't already. In general, good comments explain why, not what.






                  #0 check for special edge cases when non-digit
                #1. check if they are digit,
                #2. check if check the integer is between 0 and 255

                for part in arr:
                .. various conditions which return False
                return True



                IMO it would be more Pythonic to use all: I would boil the whole function down to



                    parts = ip.split('.')
                return len(parts) == 4 and all(is_valid_IPv4_address_part(part) for part in parts)





                    if len(part) > 1:
                if part[0] == '0':
                return False



                This isn't in the spec. It's a reasonable constraint, but you should check with the person who gave you the spec before writing the code, or at least put in a comment saying that you're making an assumption about the true intentions of the specifier.






                    if not part.isdigit():
                return False



                This is buggy. (Before testing I thought there was an issue which should be bounced back to the specifier. Upon testing, I found that some of my test cases caused validateIP to throw an exception).



                What is the expected output for these test cases?



                ¹.¹.¹.¹
                ١.١.١.١
                𝟣.𝟣.𝟣.𝟣
                ①.①.①.①





                share|improve this answer









                $endgroup$




                def validateIP(ip):



                I would expect a name starting is (a useful hint that it returns a Boolean rather than some more complex validation data structure) and explicitly mentioning IP v4 (since the current name is misleading). E.g. is_valid_IPv4_address.






                  #split them by '.' , and store them in an array
                #check the array if the length is 4 length
                arr = ip.split('.')
                if len(arr) != 4:
                return False



                The comments don't tell me anything which the code doesn't already. In general, good comments explain why, not what.






                  #0 check for special edge cases when non-digit
                #1. check if they are digit,
                #2. check if check the integer is between 0 and 255

                for part in arr:
                .. various conditions which return False
                return True



                IMO it would be more Pythonic to use all: I would boil the whole function down to



                    parts = ip.split('.')
                return len(parts) == 4 and all(is_valid_IPv4_address_part(part) for part in parts)





                    if len(part) > 1:
                if part[0] == '0':
                return False



                This isn't in the spec. It's a reasonable constraint, but you should check with the person who gave you the spec before writing the code, or at least put in a comment saying that you're making an assumption about the true intentions of the specifier.






                    if not part.isdigit():
                return False



                This is buggy. (Before testing I thought there was an issue which should be bounced back to the specifier. Upon testing, I found that some of my test cases caused validateIP to throw an exception).



                What is the expected output for these test cases?



                ¹.¹.¹.¹
                ١.١.١.١
                𝟣.𝟣.𝟣.𝟣
                ①.①.①.①






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 5 hours ago









                Peter TaylorPeter Taylor

                18.2k2963




                18.2k2963

























                    7












                    $begingroup$



                    1. A doc string reads nicer then # blockcomments



                      Consider making a doc string of that function, so you can do help(validate_ip) and it will print the doc string in the interpreter.




                    2. Adhere to PEP8



                      Functions and variables should be snake_case ie def validate_ip(ip):



                    3. You could use the all keyword to check if each part is correct; this will return False for the first failure.



                    4. Make actual tests that ensure validity



                      Instead of printing tests, make actual tests either with assert or the modules doctest or unittest.




                    5. There is a module that does this for you



                      Python is often described as "batteries included", and here you could use the ipaddress module, which will validate an IP when you create the IPv4Adress object.




                    Reworked code



                    import doctest

                    def validate_ip(ip):
                    """
                    Checks if the ip address is valid
                    args:
                    ip (str): The IP address
                    ret:
                    A boolean: True for a a valid IP

                    >>> validate_ip('08.0.0.0')
                    False

                    >>> validate_ip('192.169.0.1')
                    True

                    >>> validate_ip('0.0.0.0')
                    True

                    >>> validate_ip('192.168.123.456')
                    False

                    >>> validate_ip('oooh.0.0.1')
                    False
                    """
                    ranges = ip.split('.')
                    return len(ranges) == 4
                    and all(
                    r.isdigit() and # Check for digits
                    int(r) in range(0, 256) and # Check in range of 0-255
                    (r[0] != "0" or len(r) == 1) # Check for leading zero's
                    for r in ranges
                    )

                    if __name__ == '__main__':
                    doctest.testmod()


                    ipaddress module



                    from ipaddress import IPv4Address

                    def is_valid_ip(ip):
                    try:
                    IPv4Address(ip)
                    return True
                    except ValueError:
                    return False





                    share|improve this answer











                    $endgroup$













                    • $begingroup$
                      As a bonus, docstrings are picked up by Python's built-in help mechanisms.
                      $endgroup$
                      – Alex
                      6 hours ago










                    • $begingroup$
                      @Alex I did mention help
                      $endgroup$
                      – Ludisposed
                      6 hours ago










                    • $begingroup$
                      Sorry, must have skipped over this.
                      $endgroup$
                      – Alex
                      6 hours ago
















                    7












                    $begingroup$



                    1. A doc string reads nicer then # blockcomments



                      Consider making a doc string of that function, so you can do help(validate_ip) and it will print the doc string in the interpreter.




                    2. Adhere to PEP8



                      Functions and variables should be snake_case ie def validate_ip(ip):



                    3. You could use the all keyword to check if each part is correct; this will return False for the first failure.



                    4. Make actual tests that ensure validity



                      Instead of printing tests, make actual tests either with assert or the modules doctest or unittest.




                    5. There is a module that does this for you



                      Python is often described as "batteries included", and here you could use the ipaddress module, which will validate an IP when you create the IPv4Adress object.




                    Reworked code



                    import doctest

                    def validate_ip(ip):
                    """
                    Checks if the ip address is valid
                    args:
                    ip (str): The IP address
                    ret:
                    A boolean: True for a a valid IP

                    >>> validate_ip('08.0.0.0')
                    False

                    >>> validate_ip('192.169.0.1')
                    True

                    >>> validate_ip('0.0.0.0')
                    True

                    >>> validate_ip('192.168.123.456')
                    False

                    >>> validate_ip('oooh.0.0.1')
                    False
                    """
                    ranges = ip.split('.')
                    return len(ranges) == 4
                    and all(
                    r.isdigit() and # Check for digits
                    int(r) in range(0, 256) and # Check in range of 0-255
                    (r[0] != "0" or len(r) == 1) # Check for leading zero's
                    for r in ranges
                    )

                    if __name__ == '__main__':
                    doctest.testmod()


                    ipaddress module



                    from ipaddress import IPv4Address

                    def is_valid_ip(ip):
                    try:
                    IPv4Address(ip)
                    return True
                    except ValueError:
                    return False





                    share|improve this answer











                    $endgroup$













                    • $begingroup$
                      As a bonus, docstrings are picked up by Python's built-in help mechanisms.
                      $endgroup$
                      – Alex
                      6 hours ago










                    • $begingroup$
                      @Alex I did mention help
                      $endgroup$
                      – Ludisposed
                      6 hours ago










                    • $begingroup$
                      Sorry, must have skipped over this.
                      $endgroup$
                      – Alex
                      6 hours ago














                    7












                    7








                    7





                    $begingroup$



                    1. A doc string reads nicer then # blockcomments



                      Consider making a doc string of that function, so you can do help(validate_ip) and it will print the doc string in the interpreter.




                    2. Adhere to PEP8



                      Functions and variables should be snake_case ie def validate_ip(ip):



                    3. You could use the all keyword to check if each part is correct; this will return False for the first failure.



                    4. Make actual tests that ensure validity



                      Instead of printing tests, make actual tests either with assert or the modules doctest or unittest.




                    5. There is a module that does this for you



                      Python is often described as "batteries included", and here you could use the ipaddress module, which will validate an IP when you create the IPv4Adress object.




                    Reworked code



                    import doctest

                    def validate_ip(ip):
                    """
                    Checks if the ip address is valid
                    args:
                    ip (str): The IP address
                    ret:
                    A boolean: True for a a valid IP

                    >>> validate_ip('08.0.0.0')
                    False

                    >>> validate_ip('192.169.0.1')
                    True

                    >>> validate_ip('0.0.0.0')
                    True

                    >>> validate_ip('192.168.123.456')
                    False

                    >>> validate_ip('oooh.0.0.1')
                    False
                    """
                    ranges = ip.split('.')
                    return len(ranges) == 4
                    and all(
                    r.isdigit() and # Check for digits
                    int(r) in range(0, 256) and # Check in range of 0-255
                    (r[0] != "0" or len(r) == 1) # Check for leading zero's
                    for r in ranges
                    )

                    if __name__ == '__main__':
                    doctest.testmod()


                    ipaddress module



                    from ipaddress import IPv4Address

                    def is_valid_ip(ip):
                    try:
                    IPv4Address(ip)
                    return True
                    except ValueError:
                    return False





                    share|improve this answer











                    $endgroup$





                    1. A doc string reads nicer then # blockcomments



                      Consider making a doc string of that function, so you can do help(validate_ip) and it will print the doc string in the interpreter.




                    2. Adhere to PEP8



                      Functions and variables should be snake_case ie def validate_ip(ip):



                    3. You could use the all keyword to check if each part is correct; this will return False for the first failure.



                    4. Make actual tests that ensure validity



                      Instead of printing tests, make actual tests either with assert or the modules doctest or unittest.




                    5. There is a module that does this for you



                      Python is often described as "batteries included", and here you could use the ipaddress module, which will validate an IP when you create the IPv4Adress object.




                    Reworked code



                    import doctest

                    def validate_ip(ip):
                    """
                    Checks if the ip address is valid
                    args:
                    ip (str): The IP address
                    ret:
                    A boolean: True for a a valid IP

                    >>> validate_ip('08.0.0.0')
                    False

                    >>> validate_ip('192.169.0.1')
                    True

                    >>> validate_ip('0.0.0.0')
                    True

                    >>> validate_ip('192.168.123.456')
                    False

                    >>> validate_ip('oooh.0.0.1')
                    False
                    """
                    ranges = ip.split('.')
                    return len(ranges) == 4
                    and all(
                    r.isdigit() and # Check for digits
                    int(r) in range(0, 256) and # Check in range of 0-255
                    (r[0] != "0" or len(r) == 1) # Check for leading zero's
                    for r in ranges
                    )

                    if __name__ == '__main__':
                    doctest.testmod()


                    ipaddress module



                    from ipaddress import IPv4Address

                    def is_valid_ip(ip):
                    try:
                    IPv4Address(ip)
                    return True
                    except ValueError:
                    return False






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited 6 hours ago









                    Toby Speight

                    26.6k742118




                    26.6k742118










                    answered 6 hours ago









                    LudisposedLudisposed

                    9,06822267




                    9,06822267












                    • $begingroup$
                      As a bonus, docstrings are picked up by Python's built-in help mechanisms.
                      $endgroup$
                      – Alex
                      6 hours ago










                    • $begingroup$
                      @Alex I did mention help
                      $endgroup$
                      – Ludisposed
                      6 hours ago










                    • $begingroup$
                      Sorry, must have skipped over this.
                      $endgroup$
                      – Alex
                      6 hours ago


















                    • $begingroup$
                      As a bonus, docstrings are picked up by Python's built-in help mechanisms.
                      $endgroup$
                      – Alex
                      6 hours ago










                    • $begingroup$
                      @Alex I did mention help
                      $endgroup$
                      – Ludisposed
                      6 hours ago










                    • $begingroup$
                      Sorry, must have skipped over this.
                      $endgroup$
                      – Alex
                      6 hours ago
















                    $begingroup$
                    As a bonus, docstrings are picked up by Python's built-in help mechanisms.
                    $endgroup$
                    – Alex
                    6 hours ago




                    $begingroup$
                    As a bonus, docstrings are picked up by Python's built-in help mechanisms.
                    $endgroup$
                    – Alex
                    6 hours ago












                    $begingroup$
                    @Alex I did mention help
                    $endgroup$
                    – Ludisposed
                    6 hours ago




                    $begingroup$
                    @Alex I did mention help
                    $endgroup$
                    – Ludisposed
                    6 hours ago












                    $begingroup$
                    Sorry, must have skipped over this.
                    $endgroup$
                    – Alex
                    6 hours ago




                    $begingroup$
                    Sorry, must have skipped over this.
                    $endgroup$
                    – Alex
                    6 hours ago


















                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Code Review Stack Exchange!


                    • 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.


                    Use MathJax to format equations. MathJax reference.


                    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%2fcodereview.stackexchange.com%2fquestions%2f216311%2fvalidate-ip4-address%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

                    Færeyskur hestur Heimild | Tengill | Tilvísanir | LeiðsagnarvalRossið - síða um færeyska hrossið á færeyskuGott ár hjá færeyska hestinum

                    He _____ here since 1970 . Answer needed [closed]What does “since he was so high” mean?Meaning of “catch birds for”?How do I ensure “since” takes the meaning I want?“Who cares here” meaningWhat does “right round toward” mean?the time tense (had now been detected)What does the phrase “ring around the roses” mean here?Correct usage of “visited upon”Meaning of “foiled rail sabotage bid”It was the third time I had gone to Rome or It is the third time I had been to Rome

                    Slayer Innehåll Historia | Stil, komposition och lyrik | Bandets betydelse och framgångar | Sidoprojekt och samarbeten | Kontroverser | Medlemmar | Utmärkelser och nomineringar | Turnéer och festivaler | Diskografi | Referenser | Externa länkar | Navigeringsmenywww.slayer.net”Metal Massacre vol. 1””Metal Massacre vol. 3””Metal Massacre Volume III””Show No Mercy””Haunting the Chapel””Live Undead””Hell Awaits””Reign in Blood””Reign in Blood””Gold & Platinum – Reign in Blood””Golden Gods Awards Winners”originalet”Kerrang! Hall Of Fame””Slayer Looks Back On 37-Year Career In New Video Series: Part Two””South of Heaven””Gold & Platinum – South of Heaven””Seasons in the Abyss””Gold & Platinum - Seasons in the Abyss””Divine Intervention””Divine Intervention - Release group by Slayer””Gold & Platinum - Divine Intervention””Live Intrusion””Undisputed Attitude””Abolish Government/Superficial Love””Release “Slatanic Slaughter: A Tribute to Slayer” by Various Artists””Diabolus in Musica””Soundtrack to the Apocalypse””God Hates Us All””Systematic - Relationships””War at the Warfield””Gold & Platinum - War at the Warfield””Soundtrack to the Apocalypse””Gold & Platinum - Still Reigning””Metallica, Slayer, Iron Mauden Among Winners At Metal Hammer Awards””Eternal Pyre””Eternal Pyre - Slayer release group””Eternal Pyre””Metal Storm Awards 2006””Kerrang! Hall Of Fame””Slayer Wins 'Best Metal' Grammy Award””Slayer Guitarist Jeff Hanneman Dies””Bullet-For My Valentine booed at Metal Hammer Golden Gods Awards””Unholy Aliance””The End Of Slayer?””Slayer: We Could Thrash Out Two More Albums If We're Fast Enough...””'The Unholy Alliance: Chapter III' UK Dates Added”originalet”Megadeth And Slayer To Co-Headline 'Canadian Carnage' Trek”originalet”World Painted Blood””Release “World Painted Blood” by Slayer””Metallica Heading To Cinemas””Slayer, Megadeth To Join Forces For 'European Carnage' Tour - Dec. 18, 2010”originalet”Slayer's Hanneman Contracts Acute Infection; Band To Bring In Guest Guitarist””Cannibal Corpse's Pat O'Brien Will Step In As Slayer's Guest Guitarist”originalet”Slayer’s Jeff Hanneman Dead at 49””Dave Lombardo Says He Made Only $67,000 In 2011 While Touring With Slayer””Slayer: We Do Not Agree With Dave Lombardo's Substance Or Timeline Of Events””Slayer Welcomes Drummer Paul Bostaph Back To The Fold””Slayer Hope to Unveil Never-Before-Heard Jeff Hanneman Material on Next Album””Slayer Debut New Song 'Implode' During Surprise Golden Gods Appearance””Release group Repentless by Slayer””Repentless - Slayer - Credits””Slayer””Metal Storm Awards 2015””Slayer - to release comic book "Repentless #1"””Slayer To Release 'Repentless' 6.66" Vinyl Box Set””BREAKING NEWS: Slayer Announce Farewell Tour””Slayer Recruit Lamb of God, Anthrax, Behemoth + Testament for Final Tour””Slayer lägger ner efter 37 år””Slayer Announces Second North American Leg Of 'Final' Tour””Final World Tour””Slayer Announces Final European Tour With Lamb of God, Anthrax And Obituary””Slayer To Tour Europe With Lamb of God, Anthrax And Obituary””Slayer To Play 'Last French Show Ever' At Next Year's Hellfst””Slayer's Final World Tour Will Extend Into 2019””Death Angel's Rob Cavestany On Slayer's 'Farewell' Tour: 'Some Of Us Could See This Coming'””Testament Has No Plans To Retire Anytime Soon, Says Chuck Billy””Anthrax's Scott Ian On Slayer's 'Farewell' Tour Plans: 'I Was Surprised And I Wasn't Surprised'””Slayer””Slayer's Morbid Schlock””Review/Rock; For Slayer, the Mania Is the Message””Slayer - Biography””Slayer - Reign In Blood”originalet”Dave Lombardo””An exclusive oral history of Slayer”originalet”Exclusive! Interview With Slayer Guitarist Jeff Hanneman”originalet”Thinking Out Loud: Slayer's Kerry King on hair metal, Satan and being polite””Slayer Lyrics””Slayer - Biography””Most influential artists for extreme metal music””Slayer - Reign in Blood””Slayer guitarist Jeff Hanneman dies aged 49””Slatanic Slaughter: A Tribute to Slayer””Gateway to Hell: A Tribute to Slayer””Covered In Blood””Slayer: The Origins of Thrash in San Francisco, CA.””Why They Rule - #6 Slayer”originalet”Guitar World's 100 Greatest Heavy Metal Guitarists Of All Time”originalet”The fans have spoken: Slayer comes out on top in readers' polls”originalet”Tribute to Jeff Hanneman (1964-2013)””Lamb Of God Frontman: We Sound Like A Slayer Rip-Off””BEHEMOTH Frontman Pays Tribute To SLAYER's JEFF HANNEMAN””Slayer, Hatebreed Doing Double Duty On This Year's Ozzfest””System of a Down””Lacuna Coil’s Andrea Ferro Talks Influences, Skateboarding, Band Origins + More””Slayer - Reign in Blood””Into The Lungs of Hell””Slayer rules - en utställning om fans””Slayer and Their Fans Slashed Through a No-Holds-Barred Night at Gas Monkey””Home””Slayer””Gold & Platinum - The Big 4 Live from Sofia, Bulgaria””Exclusive! Interview With Slayer Guitarist Kerry King””2008-02-23: Wiltern, Los Angeles, CA, USA””Slayer's Kerry King To Perform With Megadeth Tonight! - Oct. 21, 2010”originalet”Dave Lombardo - Biography”Slayer Case DismissedArkiveradUltimate Classic Rock: Slayer guitarist Jeff Hanneman dead at 49.”Slayer: "We could never do any thing like Some Kind Of Monster..."””Cannibal Corpse'S Pat O'Brien Will Step In As Slayer'S Guest Guitarist | The Official Slayer Site”originalet”Slayer Wins 'Best Metal' Grammy Award””Slayer Guitarist Jeff Hanneman Dies””Kerrang! Awards 2006 Blog: Kerrang! Hall Of Fame””Kerrang! Awards 2013: Kerrang! Legend”originalet”Metallica, Slayer, Iron Maien Among Winners At Metal Hammer Awards””Metal Hammer Golden Gods Awards””Bullet For My Valentine Booed At Metal Hammer Golden Gods Awards””Metal Storm Awards 2006””Metal Storm Awards 2015””Slayer's Concert History””Slayer - Relationships””Slayer - Releases”Slayers officiella webbplatsSlayer på MusicBrainzOfficiell webbplatsSlayerSlayerr1373445760000 0001 1540 47353068615-5086262726cb13906545x(data)6033143kn20030215029