Back to Projects

Syntecxhub_Project_PortScanner

Multi-threaded TCP port scanner built with Python for network security analysis

0
Stars
0
Forks
0
Watchers
0
Open Issues

README.md

# TCP Port Scanner

A multi-threaded TCP port scanner built with Python that checks for open ports on target hosts. This tool demonstrates socket programming, concurrency using threads, and exception handling.

## Features

- 🚀 **Multi-threaded scanning** - Fast concurrent port scanning using thread pools
- 🎯 **Flexible port ranges** - Scan single ports or ranges
- 📊 **Detailed logging** - Results logged to file and console
- ⚡ **Customizable settings** - Adjustable timeout and thread count
- 🛡️ **Error handling** - Robust exception handling for network issues
- 📝 **Service detection** - Identifies common services running on open ports

## Prerequisites

- Python 3.6 or higher
- No external dependencies required (uses only Python standard library)

## Installation

1. Clone this repository:
```bash
git clone https://github.com/yourusername/tcp-port-scanner.git
cd tcp-port-scanner
```

2. Make the script executable (Linux/Mac):
```bash
chmod +x port_scanner.py
```

## Usage

### Basic Syntax

```bash
python3 port_scanner.py -t <target> -p <ports> [options]
```

### Required Arguments

- `-t, --target` - Target host (IP address or domain name)
- `-p, --ports` - Port(s) to scan (single port or range)

### Optional Arguments

- `-T, --threads` - Number of threads (default: 100)
- `--timeout` - Socket timeout in seconds (default: 1.0)
- `-v, --verbose` - Enable verbose output
- `-h, --help` - Show help message

## Examples

### Scan a Single Port

```bash
python3 port_scanner.py -t 192.168.1.1 -p 80
```

### Scan a Range of Ports

```bash
python3 port_scanner.py -t example.com -p 1-1000
```

### Scan Common Ports with Custom Settings

```bash
python3 port_scanner.py -t scanme.nmap.org -p 20-25,80,443 -T 200 --timeout 0.5
```

### Verbose Scan

```bash
python3 port_scanner.py -t 192.168.1.1 -p 1-100 -v
```

### Quick Scan of Well-Known Ports

```bash
python3 port_scanner.py -t 10.0.0.1 -p 1-1024 -T 500 --timeout 0.3
```

## Sample Output

```
    ╔═══════════════════════════════════════════════╗
    ║         TCP Port Scanner v1.0                 ║
    ║         Multi-threaded Port Scanner           ║
    ╚═══════════════════════════════════════════════╝

============================================================
Starting TCP Port Scan
Target: scanme.nmap.org (45.33.32.156)
Port Range: 1-100
Timeout: 1.0s
Threads: 100
Scan started at: 2024-01-15 14:30:22
============================================================

[+] Port 22/tcp OPEN - SSH
[+] Port 80/tcp OPEN - HTTP

============================================================
SCAN COMPLETE
============================================================
Scan Duration: 2.34 seconds
Total Ports Scanned: 100
Open Ports: 2
Closed Ports: 95
Timeout Ports: 3

Open Ports Summary:
----------------------------------------
  22/tcp - SSH
  80/tcp - HTTP

Results saved to: port_scan_results.log
============================================================
```

## How It Works

### Socket Programming

The scanner uses Python's `socket` library to create TCP connections:

```python
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
result = sock.connect_ex((target_ip, port))
```

- **AF_INET** - IPv4 addressing
- **SOCK_STREAM** - TCP protocol
- **connect_ex()** - Returns 0 if connection successful (port open)

### Concurrency with Threads

The scanner uses a thread pool pattern:

1. **Queue-based work distribution** - Ports are added to a thread-safe queue
2. **Worker threads** - Multiple threads pull from the queue and scan ports
3. **Thread synchronization** - Locks ensure thread-safe printing and logging

```python
port_queue = Queue()  # Thread-safe queue
threads = []

for _ in range(max_threads):
    thread = threading.Thread(target=worker)
    thread.start()
    threads.append(thread)
```

### Exception Handling

The scanner handles three main scenarios:

- **Open ports** - Successful connection (result = 0)
- **Closed ports** - Connection refused
- **Timeouts** - No response within timeout period
- **Errors** - Socket errors and network issues

## Logging

Results are automatically saved to `port_scan_results.log` with timestamps:

```
2024-01-15 14:30:22,123 - INFO - Scan started - Target: 45.33.32.156, Ports: 1-100
2024-01-15 14:30:23,456 - INFO - Port 22/tcp is OPEN - SSH
2024-01-15 14:30:24,789 - INFO - Port 80/tcp is OPEN - HTTP
2024-01-15 14:30:25,012 - INFO - Scan completed in 2.34s
```

## Common Port Numbers

The scanner recognizes common services:

| Port | Service |
|------|---------|
| 21 | FTP |
| 22 | SSH |
| 23 | Telnet |
| 25 | SMTP |
| 53 | DNS |
| 80 | HTTP |
| 443 | HTTPS |
| 3306 | MySQL |
| 3389 | RDP |
| 5432 | PostgreSQL |

## Performance Tips

1. **Adjust thread count** - More threads = faster scans, but can overwhelm network
   - Local networks: 200-500 threads
   - Internet hosts: 50-100 threads

2. **Optimize timeout** - Lower timeout = faster scans, but may miss slow services
   - Local networks: 0.3-0.5 seconds
   - Internet hosts: 1-2 seconds

3. **Scan specific ports** - Only scan ports you need instead of full range

## Legal and Ethical Considerations

⚠️ **IMPORTANT**: Only scan networks and hosts you have permission to test.

- Unauthorized port scanning may be illegal in your jurisdiction
- Always get written permission before scanning networks you don't own
- Use responsibly and ethically
- Consider using test hosts like `scanme.nmap.org` for practice

## Troubleshooting

### "Permission Denied" Error

Some ports (< 1024) may require root privileges on Linux:
```bash
sudo python3 port_scanner.py -t target -p 1-1024
```

### High Timeout Rate

- Increase `--timeout` value
- Reduce number of threads with `-T`
- Check network connectivity

### "Failed to Resolve Hostname"

- Verify target domain name is correct
- Check DNS settings
- Try using IP address directly

## Project Structure

```
tcp-port-scanner/
├── port_scanner.py          # Main scanner script
├── README.md                # This file
├── port_scan_results.log    # Generated log file (after first run)
└── .gitignore              # Git ignore file
```

## Future Enhancements

Potential features for future versions:

- [ ] UDP port scanning
- [ ] Service version detection
- [ ] Export results to JSON/CSV
- [ ] GUI interface
- [ ] Banner grabbing
- [ ] IPv6 support
- [ ] Scan multiple hosts from file
- [ ] OS detection

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request

## License

This project is licensed under the MIT License - see below for details:

```
MIT License

Copyright (c) 2024

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```

## Acknowledgments

- Inspired by Nmap and other network scanning tools
- Built as an educational project to learn socket programming and concurrency

## Author

Created for an internship project demonstrating:
- Socket programming fundamentals
- Multi-threading and concurrency
- Network security concepts
- Python best practices

## Contact

For questions or feedback, please open an issue on GitHub.

---

**Disclaimer**: This tool is for educational purposes only. Always ensure you have proper authorization before scanning any network or system.