def unpack_sin(data): if len(data) == 6: # IPv4 (a, port) = struct.unpack("!IH", data) addr = IPy.IPint(a) elif len(data) == 18: #IPv6 (a, b, port) = struct.unpack("!QQH", data) addr = IPy.IPint(a << 64 + b) return (str(addr), port)
def check_ip_ascending(start_ip, end_ip): # check that IPs are ascending if start_ip and end_ip and IPy.IPint(start_ip, 4).int() <= IPy.IPint( end_ip, 4).int(): print "Start IP is: {0}\n".format(start_ip) print "End IP is: {0}\n\n".format(end_ip) else: print "Start IP has to be lower or equal to end IP, both IPs have to be filled" print_usage() sys.exit(2)
def get_increments(start_ip, end_ip): """ Find how many increments by 255 are in between first and last IP in the range and the rest of the IPs after subtracting all the increments :param start_ip: first IP in the range :type start_ip str :param end_ip: last IP in the range :type end_ip str :return increments, rest """ num_ips = (IPy.IPint(end_ip).int() - IPy.IPint(start_ip).int()) increments, rest = divmod(num_ips, 255) # in case range is lower then 255 return 1 increments += 1 return increments, rest
def pack_sin(sin): """Takes a sin tuple (addr, port) and packs it into a binary form. Resulting size depends on whether addr is IPv4 or IPv6.""" (addr, port) = sin addr = IPy.IPint(addr) if addr.version() == 4: return struct.pack("!IH", addr.int(), port) else: a = addr.int() return struct.pack("!QQH", a >> 64, a % 2**64, port)
def increment_range(start_ip, counter): """ Increment IP address by 255 multiple times :param start_ip: base IP to be incremented :type start_ip: str :param counter: how many times do you want to increment the IP by 255 :return:incremented IP """ incremented_ip_int = IPy.IPint(start_ip).int() + counter * 255 incremented_ip_str = IPy.intToIp(ip=incremented_ip_int, version=4) return incremented_ip_str