Skip to content

Commit 99cfed1

Browse files
author
James Hebden
committed
Faster mapping of CIDRs to IPs
1 parent 7ccee77 commit 99cfed1

File tree

1 file changed

+42
-9
lines changed

1 file changed

+42
-9
lines changed

Interlace/lib/core/input.py

Lines changed: 42 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,15 @@
11
import functools
22
import itertools
33
import os.path
4+
import socket
5+
import struct
46
import sys
5-
from io import TextIOWrapper
67
from argparse import ArgumentParser
8+
from io import TextIOWrapper
79
from random import choice
810

9-
from netaddr import (
10-
IPRange,
11-
IPSet,
12-
glob_to_iprange,
13-
)
14-
1511
from Interlace.lib.threader import Task
12+
from netaddr import IPGlob, IPRange, IPSet, glob_to_iprange
1613

1714

1815
class InputHelper(object):
@@ -34,7 +31,7 @@ def check_positive(parser, arg):
3431
ivalue = int(arg)
3532
if ivalue <= 0:
3633
raise parser.ArgumentTypeError("%s is not a valid positive integer!" % arg)
37-
except ValueError as e:
34+
except ValueError:
3835
raise parser.ArgumentValueError("%s is not a a number!" % arg)
3936

4037
return arg
@@ -50,6 +47,42 @@ def _get_files_from_directory(arg):
5047

5148
return files
5249

50+
@staticmethod
51+
def _get_ips_from_range(ip_range):
52+
ips = set()
53+
ip_range = ip_range.split("-")
54+
55+
# parsing the above structure into an array and then making into an IP address with the end value
56+
end_ip = ".".join(ip_range[0].split(".")[0:-1]) + "." + ip_range[1]
57+
58+
# creating an IPRange object to get all IPs in between
59+
range_obj = IPRange(ip_range[0], end_ip)
60+
61+
for ip in range_obj:
62+
ips.add(str(ip))
63+
64+
return ips
65+
66+
@staticmethod
67+
def _get_ips_from_glob(glob_ips):
68+
ip_glob = IPGlob(glob_ips)
69+
70+
ips = set()
71+
72+
for ip in ip_glob:
73+
ips.add(str(ip))
74+
75+
return ips
76+
77+
@staticmethod
78+
def _get_cidr_to_ips(cidr_range):
79+
(ip, cidr) = cidr_range.split("/")
80+
mask = 32 - int(cidr)
81+
first_ip = struct.unpack(">I", socket.inet_aton(ip))[0]
82+
last_ip = first_ip | ((1 << mask) - 1)
83+
ips = frozenset([socket.inet_ntoa(struct.pack('>I', x)) for x in range(first_ip, last_ip)])
84+
return ips
85+
5386
@staticmethod
5487
def _process_port(port_type):
5588
if "," in port_type:
@@ -492,7 +525,7 @@ def setup_parser():
492525
'--repeat', dest='repeat',
493526
help='repeat the given command x number of times.'
494527
)
495-
528+
496529
output_types = parser.add_mutually_exclusive_group()
497530
output_types.add_argument(
498531
'-v', '--verbose', dest='verbose', action='store_true', default=False,

0 commit comments

Comments
 (0)