Files
python-cybersecurity/cheat_cheat/socket.md
2026-04-23 17:59:56 +02:00

154 lines
2.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
The `socket` module is where Python stops being polite and starts speaking raw network 🧩📡
Heres a **clean, practical cheat sheet** youll actually use when building cyber tools.
---
# 🐍 `socket` Cheat Sheet (Cybersecurity Edition)
## 🔌 Create a Socket
```python
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
```
* `AF_INET` → IPv4
* `SOCK_STREAM` → TCP
* (use `SOCK_DGRAM` for UDP)
---
## 🌐 Connect to a Target (Client)
```python
s.connect(("127.0.0.1", 80))
```
👉 Used in:
* Port scanners
* Banner grabbing
---
## 📤 Send Data
```python
s.send(b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n")
```
* Must be **bytes** (`b""`)
---
## 📥 Receive Data
```python
response = s.recv(1024)
print(response.decode())
```
* `1024` = buffer size
---
## ❌ Close Connection
```python
s.close()
```
---
# 🔍 Port Scanner Example (core pattern)
```python
import socket
target = "127.0.0.1"
for port in range(1, 1025):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
result = s.connect_ex((target, port))
if result == 0:
print(f"Port {port} is open")
s.close()
```
🔥 Key trick:
* `connect_ex()` returns `0` if open (no crash, cleaner)
---
# ⏱️ Timeout (avoid freezing forever)
```python
s.settimeout(1)
```
Without this, your scanner becomes a fossil 🦴
---
# 🖥️ Simple Server (Listener)
```python
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("0.0.0.0", 4444))
s.listen(1)
conn, addr = s.accept()
print(f"Connection from {addr}")
data = conn.recv(1024)
print(data.decode())
conn.close()
```
👉 Used in:
* Backdoor simulations
* Reverse shells (ethical labs only)
---
# 📡 UDP Socket (connectionless)
```python
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto(b"Hello", ("127.0.0.1", 53))
```
---
# 🧠 Useful Methods Quick List
* `socket()` → create socket
* `connect()` → connect to server
* `connect_ex()` → safer connect
* `send()` / `sendall()` → send data
* `recv()` → receive data
* `bind()` → attach to IP/port
* `listen()` → wait for connections
* `accept()` → accept connection
* `close()` → close socket
---
# ⚠️ Common Mistakes
* Forgetting `.close()` → zombie sockets
* Not using timeout → slow scans
* Sending string instead of bytes → 💥 error
* Scanning too fast → gets blocked