0

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
asked Aug 10, 2018 at 6:27

4 Answers 4

3

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
answered Aug 10, 2018 at 6:36
Sign up to request clarification or add additional context in comments.

1 Comment

i didn't know there is library for that, expected nothing less from python :)
1

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
answered Aug 10, 2018 at 6:33

Comments

0

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)
answered Aug 10, 2018 at 6:38

Comments

0

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
answered Aug 10, 2018 at 7:17

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.