port scanning Code Review with summary
Port Scanning: Port scanning is a method used for discovering open ports and services available on a networked system. A port is like a door on a computer through which data can pass. Each service or application running on a system typically listens on specific ports. By scanning ports, one can identify which services are running and potentially vulnerable to exploitation.
Query Code: This indicates the code or script that performs the port scanning. It could be written in various programming languages such as Python, Java, or C.
Now, let's delve deeper into the meaning of the components of a typical port scanning query code:
Target Host/Address: The script needs to know the target IP address or hostname to scan. This is the system or network that you want to scan for open ports.
Port Range: The script usually specifies a range of ports to scan. For example, it might scan ports 1 through 1024 (known as well-known ports) or a larger range depending on the scope of the scan.
Scanning Logic: This part of the code is responsible for iterating through the specified port range and attempting to establish connections with each port on the target system. Depending on the type of port scan (TCP, UDP, SYN, etc.), the logic might differ slightly.
Handling Responses: The code needs to handle the responses received from the target system for each port scanned. Depending on whether a connection was successfully established or not, the script may classify the port as open, closed, filtered, or some other state.
Output: Finally, the script usually produces some form of output to display the results of the port scan. This could be simple text output indicating which ports are open, closed, etc., or it could be more sophisticated, such as generating a report or logging the results to a file.
import socket
import argparse
def scan_ports(target_host, start_port, end_port):
try:
# Resolve target host to IP address
target_ip = socket.gethostbyname(target_host)
# Scan ports
for port in range(start_port, end_port + 1):
# Create socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(1)
# Attempt to connect to the port
result = s.connect_ex((target_ip, port))
if result == 0:
print(f"Port {port} is open")
s.close()
except KeyboardInterrupt:
print("\nExiting...")
exit()
except socket.gaierror:
print("Hostname could not be resolved. Exiting...")
exit()
except socket.error:
print("Couldn't connect to server. Exiting...")
exit()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="TCP Port Scanner")
parser.add_argument("host", help="Target host to scan")
parser.add_argument("start_port", type=int, help="Start port")
parser.add_argument("end_port", type=int, help="End port")
args = parser.parse_args()
scan_ports(args.host, args.start_port, args.end_port)
Comments
Post a Comment