Python and Networking – Sockets Programming 101
Sockets are one of the foundational building blocks for network communication. In Python, the socket
module allows you to create clients and servers that communicate over TCP or UDP. This tutorial will introduce you to the basics of socket programming, ideal for ethical hackers, cybersecurity professionals, and automation enthusiasts.
What is a Socket?
A socket is a software endpoint that establishes bidirectional communication between a server and one or more clients. In Python, the socket
module provides a standard way to work with low-level networking.
1. Socket
Overview:
- Module to create & manage network connections.
- Low-level interface to BSD sockets.
- Used for clients, servers, raw packet sniffers, bind shells, etc.
2. Socket Creation Syntax:
socket.socket(family=AF_INET, type=SOCK_STREAM, proto=0)
Common Parameters:
Parameter | Meaning |
---|---|
AF_INET | IPv4 |
AF_INET6 | IPv6 |
SOCK_STREAM | TCP |
SOCK_DGRAM | UDP |
SOCK_RAW | Raw access (needs root) |
proto | Usually 0 (auto selected) |
Basic Socket Functions
socket()
- Create a new socketbind()
- Bind the socket to a specific address and portlisten()
- Listen for incoming connections (server)accept()
- Accept a connection (server)connect()
- Connect to a remote socket (client)send()
andrecv()
- Send and receive data
Example 1: Basic TCP Server
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('0.0.0.0', 9999))
server.listen(5)
print("[*] Listening on port 9999")
client_socket, addr = server.accept()
print(f"[*] Accepted connection from {addr}")
client_socket.send(b"Hello from server!")
client_socket.close()
Explaination:
import socket
socket
module, which lets you do network communication (like connecting to websites or other computers).
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('0.0.0.0', 9999))
server.listen(5)
print("[*] Listening on port 9999")
client_socket, addr = server.accept()
print(f"[*] Accepted connection from {addr}")
client_socket.send(b"Hello from server!")
client_socket.close()
Summary:
This is a very basic TCP server. It:- Starts listening on port 9999.
- Waits for one client to connect.
- Sends that client a “Hello” message.
- Then closes the connection.
Example 2: Basic TCP Client
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('127.0.0.1', 9999))
response = client.recv(4096)
print(response.decode())
Explaination:
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('127.0.0.1', 9999))
response = client.recv(4096)
print(response.decode())
Summary (in real-world terms):
This client:Example: 3 Basic UDP Server
import socket
host = "127.0.0.1" # Listen on localhost
port = 4444
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((host, port)) # Bind the socket to an address and port
print(f"UDP server listening on {host}:{port}")
while True:
data, addr = sock.recvfrom(1024) # Receive data and sender's address
print(f"Received message: {data.decode()} from {addr}")
# Optional: Send a response back
sock.sendto(b"Echo: " + data, addr)
Explaination:
First: What’s different here?
Now, let’s understand the code line by line:
import socket
host = "127.0.0.1" # Listen on localhost
port = 4444
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((host, port))
print(f"UDP server listening on {host}:{port}")
while True:
data, addr = sock.recvfrom(1024)
print(f"Received message: {data.decode()} from {addr}")
sock.sendto(b"Echo: " + data, addr)
Summary:
Example: 4 Basic UDP Client
import socket
host = "127.0.0.1" # Server IP address
port = 4444
MESSAGE = b"Hello, UDP Server!"
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(MESSAGE, (host, port)) # Send data to the server
# Optional: Receive a response from the server
data, addr = sock.recvfrom(1024)
print(f"Received response: {data.decode()} from {addr}")
sock.close()
Explaination:
import socket
host = "127.0.0.1"
port = 4444
MESSAGE = b"Hello, UDP Server!"
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(MESSAGE, (host, port))
data, addr = sock.recvfrom(1024)
print(f"Received response: {data.decode()} from {addr}")
sock.close()
Summary:
This UDP client:
Common Use Cases:
- Port scanners
- Backdoors and reverse shells
- Custom servers and clients for penetration testing
- Network sniffing (in combination with other tools)
Socket Modes:
- TCP (SOCK_STREAM): Reliable, connection-based communication
- UDP (SOCK_DGRAM): Fast, connectionless communication
Conclusion:
With just a few lines of Python, you can create powerful networking tools. This is just the beginning — you can build full network scanners, web clients, or even chat apps using the socket
module. Practice by modifying and expanding these examples!
Comments
Post a Comment