Problem:
Write a python assignment where you have to enhance the port scanner code developed in class to scan IP ports. The program should ask for the IP number, starting port number, and ending port number.
After all the requisite ports are scanned, the system should print the total time it takes to do that. (Hint: Use time module)


After all, ports are scanned, prints the total time taken in seconds.

Solution:
import socket
	import time
	import sys
	from datetime import date
	if __name__ == '__main__':
	# ask for domain
	ip = input("Enter ip address or domain name to scan: ")
	# Validate that input is numeric for starting port end ending port
	try:
	port_a = int(input("Enter starting port number (1 - 65535): "))
	port_b = int(input("Enter ending port number (1 - 65535 greater than start port num): "))
	except:
	print("The input for starting port and ending port must be numeric.")
	sys.exit(1)
	# Check that starting port and ending port are between 1-65535
	if port_a not in range(1, 65535+1) or port_b not in range(1,65535+1):
	print("Starting port and ending prot must be between 1-65535.")
	sys.exit(1)
	if port_b <= port_a:
	print("Ending port number must be greater than starting port number.")
	sys.exit()
	# print info
	print('*'*30)
	print(f"List of open ports. Host:{ip} Start Port#:{port_a} End Port#:{port_b}")
	print(f"Start: {date.today()}")
	print('*'*30)
	# Save starting time
	start_time = time.time()
	for port in range(port_a, port_b+1): # iterate through ports
	print(f"Scanning port {port}", end="\r")
	try:
	a_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	a_socket.settimeout(1)
	result = a_socket.connect_ex((ip, port))
	if result == 0: # port open
	print(f"{ip}:Port:{port}")
	except socket.error as e:
	#print("time out.")
	print(e)
	finally:
	a_socket.close()
	# Save ending time
	end_time = time.time()
	# Print time taken
	print("Time taken {:.2f} seconds".format(end_time-start_time)) 
Related Samples
Explore our collection of free Python assignment samples to see examples of our expertise. These samples showcase practical applications and solutions, helping you understand our approach to Python programming assignments.
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
