Bdfy
Bdfy

Reputation: 24719

How to get list of IP addresses?

I have a range of ip addresses:

1.48.0.0 - 1.51.255.255

How to get list of IP addresses ?

Upvotes: 2

Views: 3741

Answers (6)

Wahyu Bram
Wahyu Bram

Reputation: 435

I make like this (in python3):

import ipaddress as ipaddr
from contextlib import redirect_stdout
import io



ipr = '1.48.0.0 - 1.51.255.255'
first_ip = ipr.split(' - ')[0]
last_ip = ipr.split(' - ')[1]

#change the type of first and last ip to integer

start_ipr = int(ipaddr.IPv4Address(first_range))
end_ipr = int(ipaddr.IPv4Address(last_range) + 1) #we will use range, if not giving + 1 the IP only reach 254, to make 255 add => + 1.

#after that make the list of IP with this code (redirect print stdout to memory):

f = io.StringIO()
with redirect_stdout(f):
    for ip in range(int(start_ipr), int(end_ipr)): #you see the --- for ip in range --- ? this range that i mean.
        print(ipaddr.IPv4Address(ip))
    ip_get = f.getvalue().split('\n') 

# I add .split(\n') in f.getvalue(), because the list is separate with \n, like: 1.48.0.0\n1.48.0.1\n1.48.0.2\n, etc
# with split it become: '1.48.0.0', '1.48.0.1', '1.48.0.2', etc.

# because I need to reformat it to "1.48.0.0", "1.48.0.1", 1.48.0.2", etc.
# I do this:

ips = ', '.join('"{0}"'.format(ip) for ip in ip_get)

#it will give you result: "1.48.0.0", "1.48.0.1", 1.48.0.2"
#if you need the data just type:

ip_get #or
print(ip_get)
#or need another form like have double quotes "1.48.0.1", just type:
ips #or
print(ips)

#-----------------------------------------------------------------
    #just copy this script, it will solve your problem

Upvotes: 0

Johnny
Johnny

Reputation: 2168

Get All Valid IP Addresses in a Given Range

I would use a module that has been written specifically for handling IP Addresses. A simple solution is provided by netaddr (pip install netaddr). Here's an example that will print all IP Addresses in a given range (e.g. 1.48.0.0 - 1.51.255.255):


#!/usr/bin/env python

"""Get a list of IP Addresses in a range (CIDR Notation)."""

import sys  # Using for cleanly exiting program.

try:
    # Pythonic manipulation of IPv4, IPv6, CIDR, EUI and MAC network addresses.
    from netaddr import IPNetwork

except ImportError:
    sys.exit(
        """
        Missing 'netaddr' module, get it here:

        https://pypi.python.org/pypi/netaddr
        """
    )


def get_ips(cidr_string):
    """Returns all IPv4 Addresses in a given CIDR Range
    :param cidr_string: IP Address Range in CIDR notation
    :returns: list of IP Addresses
    :rtype: list
    """

    # Cast to list for simpler manipulation.
    ip_list = list(IPNetwork(cidr_string))

    return ip_list

# Get IPs in Range '1.48.0.0 - 1.51.255.255' (Note the CIDR Notation).
ip_list = get_ips('1.48.0.0/14')

for ip_address in ip_list:

    print ip_address

Upvotes: 0

ghasem abdoli
ghasem abdoli

Reputation: 1

You can extend this code to IP form with 4 fields.

Now you can use ipRange*

startIP='0.0'
endIP = '10.10'
ipRange = []
for i in range(int(startIP.split('.')[-1]), int(endIP.split('.')[-1])):
    for j in range(int(startIP.split('.')[-2]), int(endIP.split('.')[-2])):
        ipRange.append(str(i)+ ''.join('.') + str(j))

The result is:

$ ipRange
['0.0', '0.1', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '1.0', '1.1', '1.2', '1.3', '1.4', '1.5', '1.6', '1.7', '1.8', '1.9', '2.0', '2.1', '2.2', '2.3', '2.4', '2.5', '2.6', '2.7', '2.8', '2.9', '3.0', '3.1', '3.2', '3.3', '3.4', '3.5', '3.6', '3.7', '3.8', '3.9', '4.0', '4.1', '4.2', '4.3', '4.4', '4.5', '4.6', '4.7', '4.8', '4.9', '5.0', '5.1', '5.2', '5.3', '5.4', '5.5', '5.6', '5.7', '5.8', '5.9', '6.0', '6.1', '6.2', '6.3', '6.4', '6.5', '6.6', '6.7', '6.8', '6.9', '7.0', '7.1', '7.2', '7.3', '7.4', '7.5', '7.6', '7.7', '7.8', '7.9', '8.0', '8.1', '8.2', '8.3', '8.4', '8.5', '8.6', '8.7', '8.8', '8.9', '9.0', '9.1', '9.2', '9.3', '9.4', '9.5', '9.6', '9.7', '9.8', '9.9']

Upvotes: 0

Serdalis
Serdalis

Reputation: 10489

If I understand you correctly...

start = [1,48,0,0]
end   = [1,51,255,255]

def generate_range(start, end):
    cur = start

    while cur < end:     
        cur[3] = int(cur[3]) + 1

        for pos in range(len(cur)-1, -1, -1):
            if cur[pos] == 255:
                cur[pos] = 0
                cur[pos-1] = int(cur[pos-1]) + 1

        yield '.'.join("{}".format(cur[i]) for i in range(0,len(cur)))

for x in generate_range(start, end):
    print (x)

is ugly but will do the job.
this will create a generator sequence of all the possible ip values.

be aware, this is python 3.0 code, for the best results use xrange in python 2.X


EDIT: Last version of the algorithm had a bug, this version does not

Upvotes: 2

jackdoe
jackdoe

Reputation: 1866

from struct import *
from socket import *

for ip in xrange(unpack('!I',inet_pton(AF_INET,"1.47.0.0"))[0],unpack('!I',inet_pton(AF_INET,"1.51.255.255"))[0]):
    print inet_ntop(AF_INET,pack('!I',ip));

f = unpack('!I',inet_pton(AF_INET,"1.47.0.0"))[0]
l = unpack('!I',inet_pton(AF_INET,"1.51.255.255"))[0]
while f < l:
    print inet_ntop(AF_INET,pack('!I',f));
    f = f + 1

this way it will be fairly easy to walk thru IPv6 addresses as well, but i wont recommend it because of the vastness of IPv6 space.

Upvotes: 2

Ani
Ani

Reputation: 1018

I have Implemented it using simple nested while loops. Prompt me if you find any error.

a=1
b=48

while b <= 51:
    c=0
    d=0
    while c <= 255:
        d=0
        while d <= 255:
            print str(a)+"."+str(b)+"."+str(c)+"."+str(d)
            d += 1
        c += 1
    b += 1

Upvotes: 0

Related Questions