[Tutor] Re: Create list of IPs
Roel Schroeven
rschroev_nospam_ml at fastmail.fm
Sun Feb 20 16:21:00 CET 2005
Ralfas Jegorovas wrote:
> I am wondering how I would go about making a list of IPs between two set
> IPs.
# First, list2str can be written shorter
.def list2str(lst):
. return '.'.join(map(str, lst))
# The inverse of that is also needed
.def str2list(s):
. return map(int, s.split('.'))
# Note that an IP address can also be represented as an integer
.def lst2int(lst):
. return (lst[0] << 24) | (lst[1] << 16) | (lst[2] << 8) | lst[3]
# Reverse:
.def lst2int(ip_int):
. return map(int, [ip_int >> 24,
. (ip_int >> 16) & 0xff,
. (ip_int >> 8) & 0xff,
. ip_int & 0xff])
# Once the IP addresses are converted to integers, we can simply
# loop from the first to the second
.def generate_iplist(minip, maxip):
. iplist = []
. minip_int = lst2int(str2list(minip))
. maxip_int = lst2int(str2list(maxip))
. for ip in range(minip_int, maxip_int+1):
. iplist.append(list2str(int2lst(ip)))
. return iplist
# Example:
.>>> if __name__ == '__main__':
. for ip in generate_iplist('1.0.0.250', '1.0.1.5'):
. print ip
1.0.0.250
1.0.0.251
1.0.0.252
1.0.0.253
1.0.0.254
1.0.0.255
1.0.1.0
1.0.1.1
1.0.1.2
1.0.1.3
1.0.1.4
1.0.1.5
--
"Codito ergo sum"
Roel Schroeven
More information about the Tutor
mailing list