Concept Explanation
Imagine you are writing a letter to a friend.
- Address: You need to know where they live (IP Address).
- Door: Their house might have many doors—one for mail, one for deliveries, one for guests. You need to know which door to knock on (Port Number).
- Conversation: Once the door opens, you need a way to talk (Protocol).
A Socket is the combination of an IP Address and a Port Number. It is the absolute lowest level of networking in Python. Every time you visit a website, send an email, or play an online game, your computer is opening and closing sockets behind the scenes to move data.
Syntax or Core Structure
The Socket Lifecycle
- Create: Initialize the socket object.
- Bind/Connect: Tell the socket which address and port to use.
- Listen (Server): Wait for someone to talk to you.
- Send/Receive: Exchange data (usually as bytes).
- Close: Hang up the phone.
import socket
# 1. AF_INET = IPv4, SOCK_STREAM = TCP (Reliable)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 2. Get the address of a website
host = "www.google.com"
port = 80 # Standard Web Port
# 3. Connect
s.connect((host, port))
print("Successfully connected!")
s.close()
Code Example #1 (Basic)
Building a simple Server.
import socket
# Create a TCP/IP socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the address and port
server.bind(('localhost', 12345))
# Listen for incoming connections (allow 1 person in queue)
server.listen(1)
print("Server is waiting for a connection...")
while True:
connection, address = server.accept()
print(f"Connected by {address}")
# Send a greeting
connection.sendall(b"Hello! You are connected to the Python Server.")
connection.close()
break # Stop after one connection for this demo
Code Example #2 (Intermediate)
Building a Client to talk to that server.
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('localhost', 12345))
# Receive up to 1024 bytes
data = client.recv(1024)
print(f"Received from server: {data.decode()}")
client.close()
Real World Example
A Simple HTTP Fetcher: Downloading a website's raw content without using the requests library.
import socket
def get_google_homepage():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("www.google.com", 80))
# Send an HTTP GET request manually
request = "GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n"
s.send(request.encode())
# Receive the response
response = s.recv(4096)
print(response.decode())
s.close()
# get_google_homepage()
Common Mistakes
- Address Already in Use: If you stop your server and restart it too fast, you'll get an error. Use
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)to fix this. - Sending Strings: Sockets only move Bytes. You must use
data.encode()before sending anddata.decode()after receiving. - Blocking: By default,
recv()waits forever until data arrives. If the other person never speaks, your program will freeze.
Best Practices
- Always use
try...finally: Ensure the socket is closed even if the program crashes. - Use Context Managers: Modern Python supports
with socket.socket(...) as s:. - Port Numbers: Avoid using ports below 1024 (System ports). Use ports like 8080, 12345, or 5000 for your projects.
Practice Exercises
- The Echo Server: Modify the server code so that it receives a message from the client and sends that exact same message back.
- Multi-Client Port: Research
threadingand modify your server so it can handle 5 different clients at the same time. - Port Scanner: Write a script that tries to connect to ports 75 through 85 on
localhostand prints which ones are "Open" or "Closed."