How to Create Socket in Python: Simple Guide with Examples
To create a socket in Python, use the
socket.socket() function from the socket module. This function creates a socket object that you can use to connect or listen for network communication.Syntax
The basic syntax to create a socket in Python is:
socket.socket(family, type): Creates a new socket object.family: Specifies the address family, usuallysocket.AF_INETfor IPv4.type: Specifies the socket type, usuallysocket.SOCK_STREAMfor TCP orsocket.SOCK_DGRAMfor UDP.
python
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)Example
This example creates a TCP socket, connects to example.com on port 80, sends a simple HTTP GET request, and prints the response.
python
import socket # Create a TCP/IP socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect to example.com on port 80 s.connect(('example.com', 80)) # Send HTTP GET request request = 'GET / HTTP/1.1\r\nHost: example.com\r\n\r\n' s.send(request.encode()) # Receive response response = s.recv(4096) print(response.decode()) # Close the socket s.close()
Output
<!doctype html>\n<html>\n<head>\n <title>Example Domain</title>\n ... (rest of HTTP response) ...
Common Pitfalls
Common mistakes when creating sockets include:
- Forgetting to import the
socketmodule. - Using wrong address family or socket type.
- Not closing the socket after use, which can cause resource leaks.
- Not encoding strings before sending or decoding bytes after receiving.
python
import socket # Wrong: forgetting to specify family and type # s = socket.socket() # This works but defaults may not be what you want # Right: specify family and type explicitly s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Remember to close socket s.close()
Quick Reference
| Parameter | Description | Common Values |
|---|---|---|
| family | Address family | socket.AF_INET (IPv4), socket.AF_INET6 (IPv6) |
| type | Socket type | socket.SOCK_STREAM (TCP), socket.SOCK_DGRAM (UDP) |
| socket.socket() | Creates a socket object | Use with family and type |
| connect(address) | Connects to a remote socket | address is (host, port) tuple |
| send(data) | Sends data to the socket | Data must be bytes |
| recv(bufsize) | Receives data from socket | Returns bytes |
| close() | Closes the socket | Frees resources |
Key Takeaways
Use socket.socket(family, type) to create a socket in Python.
Commonly use AF_INET for IPv4 and SOCK_STREAM for TCP sockets.
Always encode strings before sending and decode bytes after receiving.
Remember to close sockets to free system resources.
Import the socket module before creating sockets.