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

Python disappoints me. I was looking for code to scan ports, found this. I ran. the program that I used to scan. It was very fast according to python code. code below.
Can you help me speed up my code. What can I do for this?

#!/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() 
-3
source share
3 answers

You open a thousand connections one by one. This should take at least 1000 times round-trip time to the server. Python has nothing to do with it; it's just a very simple fact of networking.

What you can do to speed this up is to open connections in parallel using threads or an event-based framework, such as twisted.

+6
source

Eh, this is not Python slow. You are just trying to connect to 1000 ports at the same time.

You might be able to connect them in parallel (i.e., the connections will be non-blocking), but I think you should know a little about network programming before doing this.

+5
source

Python is slower by most standards. But it is not so slow, you noticed for most of the code. The time taken by this script is not spent by the Python interpreter, it was waiting for the completion of the I / O. Network I / O, though. You create a thousand connections and sniff each one a little, and you do it one connection at a time - it will take a lot of time, no matter what language you write it in.

+4
source

All Articles