-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetForge.py
More file actions
430 lines (363 loc) · 15.8 KB
/
NetForge.py
File metadata and controls
430 lines (363 loc) · 15.8 KB
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
"""
███╗ ██╗███████╗████████╗███████╗ ██████╗ ██████╗ ██████╗ ███████╗
████╗ ██║██╔════╝╚══██╔══╝██╔════╝██╔═══██╗██╔══██╗██╔════╝ ██╔════╝
██╔██╗ ██║█████╗ ██║ █████╗ ██║ ██║██████╔╝██║ ███╗█████╗
██║╚██╗██║██╔══╝ ██║ ██╔══╝ ██║ ██║██╔══██╗██║ ██║██╔══╝
██║ ╚████║███████╗ ██║ ██║ ╚██████╔╝██║ ██║╚██████╔╝███████╗
╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝
Forge your network, one packet at a time.
Modules:
1. Port Scanner
2. Banner Grabber
3. TCP Client/Server
4. UDP Client/Server
5. Chat Application (Multi-client)
Usage:
python socket_tool.py
"""
import socket
import threading
import sys
import time
import os
# ─────────────────────────────────────────────
# UTILS
# ─────────────────────────────────────────────
def banner():
print("\033[1;36m")
print("███╗ ██╗███████╗████████╗███████╗ ██████╗ ██████╗ ██████╗ ███████╗")
print("████╗ ██║██╔════╝╚══██╔══╝██╔════╝██╔═══██╗██╔══██╗██╔════╝ ██╔════╝")
print("██╔██╗ ██║█████╗ ██║ █████╗ ██║ ██║██████╔╝██║ ███╗█████╗ ")
print("██║╚██╗██║██╔══╝ ██║ ██╔══╝ ██║ ██║██╔══██╗██║ ██║██╔══╝ ")
print("██║ ╚████║███████╗ ██║ ██║ ╚██████╔╝██║ ██║╚██████╔╝███████╗")
print("╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝")
print("\033[0m")
print("\033[1;35m Forge your network, one packet at a time.\033[0m")
print("\033[0;90m Socket Programming Suite v1.0 | Scanner | Grabber | TCP | UDP | Chat\033[0m")
print()
def menu():
print("\033[1;33m[MAIN MENU]\033[0m")
print(" 1. Port Scanner")
print(" 2. Banner Grabber")
print(" 3. TCP Client / Server")
print(" 4. UDP Client / Server")
print(" 5. Chat Application")
print(" 0. Exit")
print()
# ─────────────────────────────────────────────
# 1. PORT SCANNER
# ─────────────────────────────────────────────
def port_scanner():
"""
Scans a target IP for open ports within a given range.
Uses non-blocking connect() with a short timeout.
"""
print("\n\033[1;32m[PORT SCANNER]\033[0m")
target = input(" Target IP : ").strip()
start = int(input(" Start Port : ").strip())
end = int(input(" End Port : ").strip())
print(f"\n Scanning {target} from port {start} to {end} ...\n")
open_ports = []
lock = threading.Lock()
def scan_port(port):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(0.5)
result = s.connect_ex((target, port))
if result == 0:
with lock:
open_ports.append(port)
print(f" \033[1;32m[OPEN]\033[0m Port {port}")
s.close()
except Exception:
pass
threads = []
for port in range(start, end + 1):
t = threading.Thread(target=scan_port, args=(port,))
threads.append(t)
t.start()
for t in threads:
t.join()
print(f"\n Scan complete. Open ports: {sorted(open_ports) if open_ports else 'None found'}\n")
# ─────────────────────────────────────────────
# 2. BANNER GRABBER
# ─────────────────────────────────────────────
def banner_grabber():
"""
Connects to a specified IP:port and retrieves the service banner.
Sends a generic HTTP HEAD request to provoke HTTP banners.
"""
print("\n\033[1;32m[BANNER GRABBER]\033[0m")
host = input(" Target IP : ").strip()
port = int(input(" Target Port : ").strip())
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(3)
s.connect((host, port))
# Send a probe to elicit HTTP/FTP/SMTP banners
try:
s.send(b"HEAD / HTTP/1.0\r\n\r\n")
except Exception:
pass
banner_data = s.recv(1024).decode(errors="ignore").strip()
s.close()
print(f"\n \033[1;33mBanner from {host}:{port}\033[0m")
print(" " + "-" * 40)
for line in banner_data.splitlines():
print(f" {line}")
print(" " + "-" * 40 + "\n")
except socket.timeout:
print(" [!] Connection timed out. No banner received.\n")
except ConnectionRefusedError:
print(" [!] Connection refused. Port may be closed.\n")
except Exception as e:
print(f" [!] Error: {e}\n")
# ─────────────────────────────────────────────
# 3. TCP CLIENT / SERVER
# ─────────────────────────────────────────────
def tcp_server():
"""
TCP Server: listens for a client, receives messages, echoes them back.
"""
port = int(input(" Server Port [default 5000]: ").strip() or "5000")
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(("0.0.0.0", port))
server.listen(1)
print(f"\n \033[1;32m[TCP SERVER]\033[0m Listening on port {port} ...")
print(" Waiting for client... (Ctrl+C to stop)\n")
try:
conn, addr = server.accept()
print(f" [+] Connected: {addr}\n")
while True:
data = conn.recv(1024)
if not data:
break
msg = data.decode().strip()
print(f" [CLIENT] {msg}")
conn.send(f"[ECHO] {msg}\n".encode())
conn.close()
except KeyboardInterrupt:
print("\n [!] Server stopped.")
finally:
server.close()
def tcp_client():
"""
TCP Client: connects to a TCP server and sends messages.
"""
host = input(" Server IP [default 127.0.0.1]: ").strip() or "127.0.0.1"
port = int(input(" Server Port [default 5000]: ").strip() or "5000")
try:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((host, port))
print(f"\n \033[1;32m[TCP CLIENT]\033[0m Connected to {host}:{port}")
print(" Type messages (empty line to quit):\n")
while True:
msg = input(" >> ").strip()
if not msg:
break
client.send(msg.encode())
reply = client.recv(1024).decode()
print(f" {reply}")
client.close()
print(" [!] Disconnected.\n")
except Exception as e:
print(f" [!] Error: {e}\n")
def tcp_menu():
print("\n\033[1;32m[TCP CLIENT / SERVER]\033[0m")
print(" 1. Start TCP Server")
print(" 2. Start TCP Client")
choice = input(" Choice: ").strip()
if choice == "1":
tcp_server()
elif choice == "2":
tcp_client()
else:
print(" Invalid option.\n")
# ─────────────────────────────────────────────
# 4. UDP CLIENT / SERVER
# ─────────────────────────────────────────────
def udp_server():
"""
UDP Server: receives datagrams and prints them.
"""
port = int(input(" Server Port [default 6000]: ").strip() or "6000")
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(("0.0.0.0", port))
print(f"\n \033[1;32m[UDP SERVER]\033[0m Listening on port {port} ...")
print(" Waiting for messages... (Ctrl+C to stop)\n")
try:
while True:
data, addr = server.recvfrom(1024)
msg = data.decode().strip()
print(f" [UDP from {addr}] {msg}")
server.sendto(f"[ACK] {msg}".encode(), addr)
except KeyboardInterrupt:
print("\n [!] Server stopped.")
finally:
server.close()
def udp_client():
"""
UDP Client: sends datagrams to a UDP server.
"""
host = input(" Server IP [default 127.0.0.1]: ").strip() or "127.0.0.1"
port = int(input(" Server Port [default 6000]: ").strip() or "6000")
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.settimeout(3)
print(f"\n \033[1;32m[UDP CLIENT]\033[0m Sending to {host}:{port}")
print(" Type messages (empty line to quit):\n")
while True:
msg = input(" >> ").strip()
if not msg:
break
client.sendto(msg.encode(), (host, port))
try:
reply, _ = client.recvfrom(1024)
print(f" {reply.decode()}")
except socket.timeout:
print(" [!] No reply (timeout).")
client.close()
print(" [!] Done.\n")
def udp_menu():
print("\n\033[1;32m[UDP CLIENT / SERVER]\033[0m")
print(" 1. Start UDP Server")
print(" 2. Start UDP Client")
choice = input(" Choice: ").strip()
if choice == "1":
udp_server()
elif choice == "2":
udp_client()
else:
print(" Invalid option.\n")
# ─────────────────────────────────────────────
# 5. CHAT APPLICATION
# ─────────────────────────────────────────────
# ── CHAT SERVER ──────────────────────────────
chat_clients = []
chat_usernames = []
def chat_broadcast(message, sender_conn=None):
"""Send message to all clients except sender."""
for c in chat_clients:
if c != sender_conn:
try:
c.send(message)
except Exception:
chat_remove(c)
def chat_remove(client):
"""Remove a disconnected client."""
if client in chat_clients:
idx = chat_clients.index(client)
username = chat_usernames[idx]
chat_clients.remove(client)
chat_usernames.remove(username)
print(f" [-] {username} disconnected")
chat_broadcast(f" *** {username} left the chat ***\n".encode())
client.close()
def chat_handle(client):
"""Handle incoming messages from a client"""
while True:
try:
message = client.recv(1024)
if not message:
break
msg = message.decode().strip()
print(f" {msg}")
chat_broadcast(f" {msg}\n".encode(), client)
except Exception:
chat_remove(client)
break
def chat_server():
"""Multi-client TCP chat server"""
port = int(input(" Chat Port [default 9988]: ").strip() or "9988")
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(("0.0.0.0", port))
server.listen()
print(f"\n \033[1;32m[CHAT SERVER]\033[0m Running on port {port} 🚀")
print(" Waiting for clients... (Ctrl+C to stop)\n")
try:
while True:
client, address = server.accept()
print(f" [+] Connection from {address}")
client.send(" Enter your name: ".encode())
username = client.recv(1024).decode().strip()
chat_usernames.append(username)
chat_clients.append(client)
print(f" [+] {username} joined ✅")
chat_broadcast(f" *** {username} joined the chat ***\n".encode())
client.send(" Welcome to the chat! Type your message:\n".encode())
t = threading.Thread(target=chat_handle, args=(client,))
t.daemon = True
t.start()
except KeyboardInterrupt:
print("\n [!] Chat server stopped.")
finally:
server.close()
# ── CHAT CLIENT ──────────────────────────────
def chat_receive(client):
"""Thread: receive and print messages """
while True:
try:
message = client.recv(1024).decode()
print(message, end="")
except Exception:
print(" [!] Disconnected from server.")
client.close()
break
def chat_write(client):
"""Thread: read input and send messages """
while True:
try:
msg = input()
if msg.strip().lower() in ("/quit", "/exit", "/leave"):
print(" [!] Leaving chat...")
client.close()
os._exit(0)
client.send(msg.encode())
except Exception:
break
def chat_client():
"""Connect to the chat server"""
host = input(" Server IP [default 127.0.0.1]: ").strip() or "127.0.0.1"
port = int(input(" Chat Port [default 9988]: ").strip() or "9988")
try:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((host, port))
print(f"\n \033[1;32m[CHAT CLIENT]\033[0m Connected to {host}:{port}")
print(" Commands: /quit or /leave to exit\n")
threading.Thread(target=chat_receive, args=(client,), daemon=True).start()
chat_write(client)
except Exception as e:
print(f" [!] Could not connect: {e}\n")
def chat_menu():
print("\n\033[1;32m[CHAT APPLICATION]\033[0m")
print(" 1. Start Chat Server")
print(" 2. Join Chat (Client)")
choice = input(" Choice: ").strip()
if choice == "1":
chat_server()
elif choice == "2":
chat_client()
else:
print(" Invalid option.\n")
# ─────────────────────────────────────────────
# MAIN
# ─────────────────────────────────────────────
def main():
banner()
while True:
menu()
choice = input(" Select option: ").strip()
print()
if choice == "1": port_scanner()
elif choice == "2": banner_grabber()
elif choice == "3": tcp_menu()
elif choice == "4": udp_menu()
elif choice == "5": chat_menu()
elif choice == "0":
print(" Goodbye!\n")
sys.exit(0)
else:
print(" [!] Invalid option. Try again.\n")
if __name__ == "__main__":
main()