Benny McFarley
Benny McFarley

Reputation: 89

Python - Create list of IPs based off starting IP

I spent a few hours researching, and this has stumped me. Before I go down a new path, I'm looking for a best practice.

I ultimately want a list of IPs (just the IPs) when given a starting IP, based off the quantity of items in a list.

I've been using the ipaddress module; here's the nearest I've gotten..

import ipaddress
IP_Start = 192.168.1.1
hostnames = [hostname1, hostname2, hostname3]
list_of_ips = []
my_range = range(len(hostnames))
for ips in my_range:
    list_of_ips.append(ipaddress.ip_address(IP_Start) + my_range[ips])
print(list_of_ips)

Output:

list_of_ips = [IPv4Address('192.168.1.1'), IPv4Address('192.168.1.2'), IPv4Address('192.168.1.3')]

For some reason, I cannot strip "IPv4Address(' ')" out of the list of strings; my output may not be a traditional list. When using str.replace, I get weird errors and figure replacing is probably not the best practice.

I feel like if I ditch the ipaddress module, there would be a much simpler way of doing this. What would be a better way of doing this so my output is simply

list_of_ips = [192.168.1.1, 192.168.1.2, 192.168.1.3]

Upvotes: 1

Views: 204

Answers (2)

Joran Beasley
Joran Beasley

Reputation: 114058

Here is how to do it with builtins only

start with a function to convert an IP address to a long integer, and another function to convert a long integer back into an IP address

import socket,struct
def ip_to_int(ip_address):
    return struct.unpack('!I', socket.inet_aton(ip_address))[0]


def int_to_ip(int_value):
    return socket.inet_ntoa(struct.pack('!I', int_value))

then all you need to do is iterate over your range

def iter_ip_range(start_address, end_address):
    for i in range(ip_to_int(start_address), ip_to_int(end_address) + 1):
        yield int_to_ip(i)

and just use it

print(list(iter_ip_range("192.168.11.12","192.168.11.22")))

Upvotes: 0

Prune
Prune

Reputation: 77880

IPv4Address is the data type of the object returned. That is the name of a class; the display function for that class says that it returns the format you see, with the IP address as a string. You need to look up the class to find a method (function) or attribute (data field) to give you the IP address as a string, without the rest of the object tagging along.

The simplest way to do this is to convert to str:

for ips in my_range:
    list_of_ips.append(str(ipaddress.ip_address(IP_Start)) ... )

Upvotes: 1

Related Questions