0

trying to create a function that takes a list of IPs, splits them at the dot and performs various checks on each group to check if it is valid. If the potential IP in the ip_list fails the checks, it then removes it from the list. That is where it falls down: it will not remove the test cases from the list of IPs. I have only included the first check as it is this one (the check to see if the potential IP is in correct format: x.x.x.x i.e 4 long) that is not working. If it is not 4 long, I want it to remove that failing address from the list of IPs:

import sys, re, os, time

def verify_ip(ip_list):
    """takes the IP addresses picked up from regex of URL source code and
       verifies they are valid IP addresses."""

    print(ip_list)
    for ip in ip_list:
        octet = ip.split('.')
        print(octet)

        if len(octet) != 4:
            return False
            ip_list.remove(ip)
    print(ip_list)

def main():

    print('\n[-]Verify IP loop TEST ENVIRONMENT [-]')
    time.sleep(1)
    ipv4_list = ['255.255.255.0','192.168.0.1','10.16.231.17',
               '257.10.7.7','126.20.20.4','10.5.5.699',
               '999.999.999.999.999','192.157.8.c']
    verify_ip(ipv4_list)

#  boilerplate
if __name__ == '__main__':
    main()

The output I receive:

[-]Verify IP loop TEST ENVIRONMENT [-]
['255.255.255.0', '192.168.0.1', '10.16.231.17', '257.10.7.7', 
'126.20.20.4', '10.5.5.699', '999.999.999.999.999', '192.157.8.c']
['255', '255', '255', '0']
['192', '168', '0', '1']
['10', '16', '231', '17']
['257', '10', '7', '7']
['126', '20', '20', '4']
['10', '5', '5', '699']
['999', '999', '999', '999', '999']
>>> 

Why is my code not taking out 999.999.999.999.999?

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
Eugeen
  • 51
  • 5
  • 1
    Just glancing at your code, you are `ip_list.remove(ip)` while you iterate over `ip_list`, which is almost certainly going to cause bugs. Don't add or remove from a list while iterating over it, unless you are very careful. Probably, it is best to build a *new list* and return it. – juanpa.arrivillaga Nov 15 '17 at 20:03
  • 1
    @juanpa.arrivillaga thankyou for the help! – Eugeen Nov 15 '17 at 20:13
  • In addition to fixing you list filtering code, i.e. put all valid addresses in "good" list and return that, you may want to use the `ipaddress` module to see if an address looks valid: https://docs.python.org/3/library/ipaddress.html – gammazero Nov 15 '17 at 20:15

0 Answers0