I am making a Python program with what I learned so far where the user enters two IPs that represents the start and end of the range of IPs to be scanned, then saves the wanted IP in a text file.
#ip range and scanning
import socket
import sys
ok=[]
def ipscan(start2,port):
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
try:
s.connect((start2,port))
print start2 ,'-->port %s is Open'%port
ok.append(start2)
except: print start2 ,'-->port %s is Closed ! '%port
def iprange(start,end):
while end>start:
start[3]+=1
ipscan('.'.join(map(str,start)),p)
for i in (3,2,1,0):
if start[i]==255:
start[i-1]+=1
start[i]=0
#--------------------------------------------#
sta=map(int,raw_input('From : ').split('.'))
fin=map(int,raw_input('to : ').split('.'))
p=input('Port to scan : ')
iprange(sta,fin)
print '-----------end--------------'
of=open('Output.txt','w')
for ip in ok:
of.writelines(ip+'\n')
of.close()
It seems to be working but I need to be sure, and wanted to know if I can make it any faster, or if there is a better way.
1 Answer 1
Your naming convention doesnt aid legability. e.g, rename p
to port
.
Don't do carte blanche exception handling. Be more specific, e.g.:
try:
...
except (ValueError, KeyError)
...
You are also a miser with your spaces. White space is important for legibility.
explicit is better than implicit so replace ipscan('.'.join(map(str,start)),p)
with ipscan(start2='.'.join(map(str,start)), port=p)
Consider replacing while end>start
with while end >= start
as it allows scanning of a single IP address..
I cans see how the ordering of 3,2,1,0 is important so replace
for i in (3,2,1,0):
if start[i]==255:
start[i-1]+=1 #what if
start[i]=0
with
for i, val in enumerate(start):
if val == 255:
start[i] = 0
start[i-1] += 1
Also, what if item at index 0 == 255? that will cause start[i-1] += 1
to raise an Index Error.
Also, it is not clear why that transformation is being done, so some documentation will be great. Future you will thank present you for it too. Just simply #this does x because of y
can suffice.
replace
of=open('Output.txt','w')
for ip in ok:
of.writelines(ip+'\n')
of.close()
with context and join
with open('Output.txt','w') as of:
of.write('\n'.join(ok))