2
\$\begingroup\$

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.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Mar 24, 2013 at 10:47
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

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))
answered Mar 25, 2013 at 13:06
\$\endgroup\$

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.