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
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
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
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)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.