How to Use Socket Module in Python: Simple Guide and Example
Use the
socket module in Python to create network connections by first creating a socket object with socket.socket(), then connecting or binding it to an address. You can send and receive data using send() and recv() methods for TCP sockets.Syntax
The basic steps to use the socket module are:
- Create a socket:
socket.socket(family, type)wherefamilyis usuallysocket.AF_INETfor IPv4 andtypeissocket.SOCK_STREAMfor TCP. - Connect or bind: Use
connect(address)for clients orbind(address)andlisten()for servers. - Send and receive data: Use
send()andrecv()for TCP sockets. - Close the socket: Use
close()when done.
python
import socket # Create a TCP/IP socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect to a server s.connect(('hostname', 80)) # Send data s.send(b'Hello') # Receive data data = s.recv(1024) # Close socket s.close()
Example
This example shows a simple TCP client that connects to example.com on port 80, sends a HTTP GET request, and prints the response.
python
import socket # Create a socket object client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect to example.com on port 80 client_socket.connect(('example.com', 80)) # Send HTTP GET request request = 'GET / HTTP/1.1\r\nHost: example.com\r\n\r\n' client_socket.send(request.encode()) # Receive response response = client_socket.recv(4096) # Print response print(response.decode()) # Close the socket client_socket.close()
Output
HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
Content-Length: ...
<!doctype html>
<html>
<head>
<title>Example Domain</title>
...
</html>
Common Pitfalls
- Not closing sockets: Always call
close()to free resources. - Blocking calls:
recv()waits for data; use timeouts or non-blocking mode if needed. - Incorrect address format: Use a tuple
(host, port)forconnect()andbind(). - Mixing UDP and TCP: Use
SOCK_DGRAMfor UDP sockets, notSOCK_STREAM.
python
import socket # Wrong: forgetting to close socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('example.com', 80)) s.send(b'Hello') # No s.close() here - resource leak # Right: closing socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('example.com', 80)) s.send(b'Hello') s.close()
Quick Reference
Here is a quick summary of common socket methods:
| Method | Description |
|---|---|
| socket.socket(family, type) | Create a new socket object |
| connect(address) | Connect to a remote socket at address |
| bind(address) | Bind socket to local address |
| listen(backlog) | Enable server to accept connections |
| accept() | Accept a connection (server side) |
| send(bytes) | Send data to the socket |
| recv(bufsize) | Receive data from the socket |
| close() | Close the socket |
Key Takeaways
Create a socket with socket.socket() specifying address family and type.
Use connect() for clients and bind() plus listen() for servers.
Send and receive data with send() and recv() methods.
Always close sockets with close() to free resources.
Be careful with blocking calls and address formats.