Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

performance - Python is a bit slow. How can I speed up this code?

Python is disappointing me. I searched a code for port scan, found this. Runned it. the program I used for scanning. It was very fast according to python code. the code is below.
Can you help me about accelerating my code. What can i du for it?.

#!/usr/bin/env python  
from socket import *   

if __name__ == '__main__':  
    target = raw_input('Enter host to scan: ')  
    targetIP = gethostbyname(target)  
    print 'Starting scan on host ', targetIP  

    #scan reserved ports  
    for i in range(20, 1025):  
        s = socket(AF_INET, SOCK_STREAM)  

        result = s.connect_ex((targetIP, i))  

        if(result == 0) :  
            print 'Port %d: OPEN' % (i,)  
        s.close()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are opening a thousand connections one after another. This has to take at least 1000 times the round trip time to the server. Python has nothing to do with it, this is just a very basic fact of networks.

What you can do to speed this up is opening the connections in parallel, using threading or a event based framework like twisted.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...