开发者

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 progr开发者_运维问答am 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()


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.


Eh, this isn't Python being slow. It's just that you're trying to connect to 1000 ports at the same time.

Maybe you could make them connect in parallel(i.e. have the connections be non-blocking), but I think you should learn a bit more about network programming before you do that.


Python is slow by most standards. But it's not so slow you notice for most code. The time this script takes isn't spent in the Python interpreter, it's spent waiting for I/O to complete. Network I/O nonetheless. You're creating a thousand connections and do some sniffing over each, and you do it one connection at a time - that's going to take a long time no matter what language you write it in.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜