Ad

Python: TypeError: Int() Argument Must Be A String Or A Number, Not 'IPv4Network'

- 1 answer

I am trying to read IP addresses from the csv and convert them to IP ranges and also arrange/group them by each category.

Below is my code:

def create_range(ip_addresses):
    groups = []
    for _, g in itertools.groupby(enumerate(sorted(ip_addresses)), lambda (i, x): i-int(x)):
       group = map(operator.itemgetter(1), g)
       if len(group) > 1:
           groups.append("{}-{}".format(group[0], str(group[-1])))
       else:
           groups.append(str(group[0]))
    return groups

ips = collections.defaultdict(list)

with open('some.csv') as csv_file:
    file_reader = csv.reader(csv_file)
    next(file_reader)
    for (ip, cat, typ) in file_reader:
        ip = ipaddress.IPv4Network(unicode(ip.strip()))
        cat = cat.strip()
        ips[cat.strip()].append(ip)
    resultIPranges = {org: create_range(ip_range) for cat, ip_range in ips.items()}

My CSV is something as follows:

csv_file = """ip, cat, typ
              50.102.182.2, myCompany, blue
              52.102.182.4, myCompany, blue
              52.102.182.1, myCompany, blue
              52.102.182.5, myCompany, blue
              52.102.182.3, myCompany, blue
              27.101.178.17, myCompany, blue
              27.101.178.16, hisComp, red
              27.101.178.15, hisComp, red
              23.201.165.7, hisComp, red
              55.200.162.10, hisComp, red
              55.200.162.12, hisComp, red
              55.200.162.13, hisComp, red
              55.200.162.11, hisComp, red
              30.101.102.4, hisComp, red
"""

Current issue/error:

for _, g in itertools.groupby(enumerate(sorted(ip_addresses)), lambda (i, x): i-int(x)): TypeError: int() argument must be a string or a number, not 'IPv4Network'

Ad

Answer

From my understanding your x is a IPv4Network instance not int; so int(x) can not convert it to int;

The things that can be converted is IPv4Address instance; So my shot is that you should change the

 ip = ipaddress.IPv4Network(unicode(ip.strip()))

to

 ip = ipaddress.IPv4Address(unicode(ip.strip()))

– opalczynski

Ad
source: stackoverflow.com
Ad