Skip to content

Instantly share code, notes, and snippets.

@anmolj7
Last active December 4, 2019 04:39
Show Gist options
  • Save anmolj7/df1610d444fda4d0433d0bcb8fb9929f to your computer and use it in GitHub Desktop.
Save anmolj7/df1610d444fda4d0433d0bcb8fb9929f to your computer and use it in GitHub Desktop.
import socket, threading
def connect(ip, port_number, delay, output):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.settimeout(delay)
try:
sock.connect((ip, port_number))
output[port_number] = True
except:
output[port_number] = False
def scan_ports(host_ip, delay, low, high):
#N is the number of ports you wanna scan, maximum value is 65535
output = {}
#Thread to scan ports
N = high-low
threads = [threading.Thread(target=connect, args=(host_ip, i, delay, output)) for i in range(low, high+1)]
#Starting thread
[threads[i].start() for i in range(N)]
#joining threads
[threads[i].join() for i in range(N)]
ports = [x for x in output if output[x]]
for i in range(len(ports)):
print(f'{i}: {ports[i]}')
def main():
host_ip = input("Enter host ip: ")
delay = int(input("Enter maximum time out: "))
low, high = map(int, input("Enter the range of ports you wanna scan seprated by a space: ").split())
assert low>=0
assert high<=65535
scan_ports(host_ip, delay, low, high)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment