File size: 11,114 Bytes
e1b4496
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
class PortScanner {
    constructor() {
        this.isScanning = false;
        this.progressInterval = null;
        this.initializeEventListeners();
    }

    initializeEventListeners() {
        // Form elements
        this.targetIpInput = document.getElementById('target-ip');
        this.startPortInput = document.getElementById('start-port');
        this.endPortInput = document.getElementById('end-port');
        this.timeoutInput = document.getElementById('timeout');
        this.threadsInput = document.getElementById('threads');
        
        // Buttons
        this.scanBtn = document.getElementById('scan-btn');
        this.pingBtn = document.getElementById('ping-btn');
        this.exportBtn = document.getElementById('export-btn');
        this.clearBtn = document.getElementById('clear-btn');
        
        // Sections
        this.progressSection = document.getElementById('progress-section');
        this.resultsSection = document.getElementById('results-section');
        
        // Event listeners
        this.scanBtn.addEventListener('click', () => this.startScan());
        this.pingBtn.addEventListener('click', () => this.pingHost());
        this.exportBtn.addEventListener('click', () => this.exportResults());
        this.clearBtn.addEventListener('click', () => this.clearResults());
        
        // Preset buttons
        document.querySelectorAll('.preset-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const start = e.target.dataset.start;
                const end = e.target.dataset.end;
                this.startPortInput.value = start;
                this.endPortInput.value = end;
            });
        });
        
        // Form validation
        this.targetIpInput.addEventListener('input', () => this.validateForm());
        this.startPortInput.addEventListener('input', () => this.validateForm());
        this.endPortInput.addEventListener('input', () => this.validateForm());
    }

    validateForm() {
        const ip = this.targetIpInput.value.trim();
        const startPort = parseInt(this.startPortInput.value);
        const endPort = parseInt(this.endPortInput.value);
        
        let isValid = true;
        
        // IP validation
        if (!ip || !this.isValidIP(ip)) {
            isValid = false;
        }
        
        // Port validation
        if (startPort < 1 || endPort > 65535 || startPort > endPort) {
            isValid = false;
        }
        
        this.scanBtn.disabled = !isValid || this.isScanning;
        return isValid;
    }

    isValidIP(ip) {
        const ipRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
        return ipRegex.test(ip);
    }

    async pingHost() {
        const ip = this.targetIpInput.value.trim();
        
        if (!ip || !this.isValidIP(ip)) {
            this.showNotification('Please enter a valid IP address', 'error');
            return;
        }
        
        this.pingBtn.disabled = true;
        this.pingBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Pinging...';
        
        try {
            const response = await fetch('/api/ping', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ ip: ip })
            });
            
            const data = await response.json();
            
            if (response.ok) {
                const status = data.status === 'reachable' ? 'Host is reachable' : 'Host appears unreachable';
                const type = data.status === 'reachable' ? 'success' : 'error';
                this.showNotification(status, type);
            } else {
                this.showNotification(data.error || 'Ping failed', 'error');
            }
        } catch (error) {
            this.showNotification('Network error during ping', 'error');
        } finally {
            this.pingBtn.disabled = false;
            this.pingBtn.innerHTML = '<i class="fas fa-satellite-dish"></i> Ping';
        }
    }

    async startScan() {
        if (!this.validateForm()) {
            this.showNotification('Please check your input values', 'error');
            return;
        }
        
        const scanData = {
            ip: this.targetIpInput.value.trim(),
            start_port: parseInt(this.startPortInput.value),
            end_port: parseInt(this.endPortInput.value),
            timeout: parseFloat(this.timeoutInput.value),
            threads: parseInt(this.threadsInput.value)
        };
        
        // Check port range limit
        const portRange = scanData.end_port - scanData.start_port + 1;
        if (portRange > 10000) {
            this.showNotification('Port range too large (max 10000 ports)', 'error');
            return;
        }
        
        this.isScanning = true;
        this.scanBtn.disabled = true;
        this.scanBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Scanning...';
        
        // Show progress section
        this.progressSection.style.display = 'block';
        this.resultsSection.style.display = 'none';
        
        // Start progress monitoring
        this.startProgressMonitoring();
        
        try {
            const response = await fetch('/api/scan', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(scanData)
            });
            
            const data = await response.json();
            
            if (response.ok) {
                this.displayResults(data);
                this.showNotification(`Scan completed! Found ${data.total_open} open ports`, 'success');
            } else {
                this.showNotification(data.error || 'Scan failed', 'error');
            }
        } catch (error) {
            this.showNotification('Network error during scan', 'error');
        } finally {
            this.stopProgressMonitoring();
            this.isScanning = false;
            this.scanBtn.disabled = false;
            this.scanBtn.innerHTML = '<i class="fas fa-search"></i> Start Scan';
            this.progressSection.style.display = 'none';
        }
    }

    startProgressMonitoring() {
        this.progressInterval = setInterval(async () => {
            try {
                const response = await fetch('/api/progress');
                const data = await response.json();
                
                const progressFill = document.getElementById('progress-fill');
                const progressText = document.getElementById('progress-text');
                
                progressFill.style.width = `${data.percentage}%`;
                progressText.textContent = `Scanning... ${data.progress}/${data.total} ports (${data.percentage}%)`;
            } catch (error) {
                console.error('Error fetching progress:', error);
            }
        }, 500);
    }

    stopProgressMonitoring() {
        if (this.progressInterval) {
            clearInterval(this.progressInterval);
            this.progressInterval = null;
        }
    }

    displayResults(data) {
        const resultsSection = document.getElementById('results-section');
        const resultsSummary = document.getElementById('results-summary');
        const resultsTableBody = document.getElementById('results-tbody');
        
        // Update summary
        resultsSummary.innerHTML = `
            <strong>Target:</strong> ${data.target_ip} | 
            <strong>Range:</strong> ${data.scan_range} | 
            <strong>Open Ports:</strong> ${data.total_open}/${data.total_scanned} | 
            <strong>Duration:</strong> ${data.scan_duration}s
        `;
        
        // Clear previous results
        resultsTableBody.innerHTML = '';
        
        // Add results to table
        if (data.open_ports && data.open_ports.length > 0) {
            data.open_ports.forEach(port => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td><strong>${port.port}</strong></td>
                    <td><span class="status-${port.status}">${port.status.toUpperCase()}</span></td>
                    <td>${port.service || 'unknown'}</td>
                    <td>TCP</td>
                `;
                resultsTableBody.appendChild(row);
            });
        } else {
            const row = document.createElement('tr');
            row.innerHTML = '<td colspan="4" style="text-align: center; color: #666;">No open ports found</td>';
            resultsTableBody.appendChild(row);
        }
        
        // Show results section
        resultsSection.style.display = 'block';
        
        // Store results for export
        this.lastScanResults = data;
    }

    exportResults() {
        if (!this.lastScanResults) {
            this.showNotification('No results to export', 'error');
            return;
        }
        
        const data = this.lastScanResults;
        let csvContent = 'Port,Status,Service,Protocol\n';
        
        if (data.open_ports && data.open_ports.length > 0) {
            data.open_ports.forEach(port => {
                csvContent += `${port.port},${port.status},${port.service || 'unknown'},TCP\n`;
            });
        }
        
        // Create and download file
        const blob = new Blob([csvContent], { type: 'text/csv' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `port_scan_${data.target_ip}_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.csv`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
        
        this.showNotification('Results exported successfully', 'success');
    }

    clearResults() {
        this.resultsSection.style.display = 'none';
        this.lastScanResults = null;
        this.showNotification('Results cleared', 'info');
    }

    showNotification(message, type = 'info') {
        const notification = document.getElementById('notification');
        notification.textContent = message;
        notification.className = `notification ${type}`;
        notification.classList.add('show');
        
        setTimeout(() => {
            notification.classList.remove('show');
        }, 4000);
    }
}

// Initialize the application when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    new PortScanner();
});

// Add some utility functions for better UX
document.addEventListener('keydown', (e) => {
    if (e.key === 'Enter' && e.target.tagName === 'INPUT') {
        const scanner = new PortScanner();
        if (scanner.validateForm()) {
            scanner.startScan();
        }
    }
});

// Auto-focus on IP input when page loads
window.addEventListener('load', () => {
    document.getElementById('target-ip').focus();
});