Anirban Singha
Anirban Singha

Reputation: 23

Get ip range from specific ip address using python

Hi I Encounter a problem while writing python program for ip address. Program is :-

ip1='192.168.0.0'
ip2='192.168.255.255'
ip1=ip1.split('.')
ip2=ip2.split('.')
while ip1[2]<=ip2[2]:
    print ip1[0]+'.'+ip1[1]+'.'+ip1[2]+'.'+ip1[3]
    ip1[2]=ip1[2]+1
while ip1[3]<=ip2[3]:
    print ip1[0]+'.'+ip1[1]+'.'+ip1[2]+'.'+ip1[3]
    ip1[3]=ip1[3]+1

This program is gives me only one result :- 192.168.0.0 Expected Ans is :-

    192.168.0.0
    192.168.0.1
    192.168.0.2
    ......
    192.168.255.255

Upvotes: 0

Views: 755

Answers (4)

Vasilis G.
Vasilis G.

Reputation: 7859

If you want your range of IP addresses to be dynamic, you can do the following:

ip1='192.168.0.0'
ip2='192.168.255.255'

first, second, thirdStart, lastStart = list(map(int,ip1.split(".")))
thirdEnd, lastEnd = list(map(int,ip2.split(".")))[2:] 

for i in range(thirdStart,thirdEnd+1,1):
    for j in range(lastStart,lastEnd+1,1):
        print(".".join(list(map(str,[first,second,i,j]))))

Output:

192.168.0.0
192.168.0.1
192.168.0.2
192.168.0.3
192.168.0.4
192.168.0.5
192.168.0.6
.
.
.
192.168.255.252
192.168.255.253
192.168.255.254
192.168.255.255

Upvotes: 0

Junhee Shin
Junhee Shin

Reputation: 758

use ipaddress module. you can check ip range easily. (range from nip1 to nip2)

import ipaddress

ip1='192.168.0.0'
ip2='192.168.255.255'


nip1 = int(ipaddress.IPv4Address(ip1))
nip2 = int(ipaddress.IPv4Address(ip2))

for n in range(nip1, nip2+1):
    add=str(ipaddress.IPv4Address(n))
    print(add)

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195653

You can use ipaddress (docs here) module builtin within Python:

import ipaddress

for address in ipaddress.ip_network('192.168.0.0/16'):
    print(address)

Prints:

192.168.0.0
192.168.0.1
192.168.0.2
192.168.0.3

...all the way to:

192.168.255.252
192.168.255.253
192.168.255.254
192.168.255.255

Upvotes: 3

Nihal
Nihal

Reputation: 5344

just use like this.

for i in range(256):
    for j in range(256):
        ip = "192.168.%d.%d" % (i, j)
        print ip

output:

192.168.0.0
192.168.0.1
192.168.0.2
192.168.0.3
192.168.0.4
.
.
192.168.255.254
192.168.255.255

Upvotes: 1

Related Questions