0
0
PythonHow-ToBeginner · 3 min read

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, usually socket.AF_INET for IPv4.
  • type: Specifies the socket type, usually socket.SOCK_STREAM for TCP or socket.SOCK_DGRAM for 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 socket module.
  • 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

ParameterDescriptionCommon Values
familyAddress familysocket.AF_INET (IPv4), socket.AF_INET6 (IPv6)
typeSocket typesocket.SOCK_STREAM (TCP), socket.SOCK_DGRAM (UDP)
socket.socket()Creates a socket objectUse with family and type
connect(address)Connects to a remote socketaddress is (host, port) tuple
send(data)Sends data to the socketData must be bytes
recv(bufsize)Receives data from socketReturns bytes
close()Closes the socketFrees 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.