Instructions
Objective
Write a python homework program to create port scanner.
Requirements and Specifications
Source Code
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 for insightful examples and solutions. These samples cover various topics and complexities to help you understand Python programming concepts effectively.
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python
Python