Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...