user127886
user127886

Reputation: 317

How can I loop through an IP address that is input by the user in python

Sorry i am new to python so I would like to inquire something. Let's say the user enter his IP ( 192.168.1.10 ), i want to start looping from his input (192.168.1.10) to the end of the sub net 192.168.1.255/24.

I was thinking something along this line

for i in range(256):
    IP = "192.168.1.%d" (i)
    print IP

But how do i put his input inside? Any guidance will be helpful, thanks.

Cheers, Tech Newbie.

Upvotes: 2

Views: 1286

Answers (3)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

Use the ipaddress module in Python 3.3. You can use an index into a subnet as a list of addresses:

>>> import ipaddress
>>> subnet = ipaddress.ip_network('192.168.1.0/24')
>>> for i in range(10, 256):
>>>     print(subnet[i])
192.168.1.10
192.168.1.11
...
192.168.1.254
192.168.1.255

Upvotes: 0

R Nar
R Nar

Reputation: 5515

Assuming that you take the initial ip address with something like

IP = raw_input('Enter your IP:')

You can rework your loop

for i in range(256):
    print(IP[:IP.rfind('.')] + '.' + i)

Upvotes: 0

Ahasanul Haque
Ahasanul Haque

Reputation: 11134

This should work for you, though I haven't tested it.

ip=raw_input("Enter an ip address:")
partToFetch= int(ip.split(".")[3])
for i in range(partToFetch,256):
    print "192.168.1.{0}".format(str(i))

Upvotes: 1

Related Questions