Socket Programming
Socket
programming.
Demonstrates basic TCP socket creation, DNS resolution, and server connection using Python's socket module, with robust error handling.
Overview
Project Overview
Demonstrates basic TCP socket creation, DNS resolution, and server connection using Python's socket module, with robust error handling.
Python
TCP/IP
DNS
Socket API
Implementation
Socket Creation
Initializes a TCP socket and handles potential creation errors:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("socket successfully created")
except socket.error as err:
print(f"socket creation failed with error {err}")
Uses socket.AF_INET for IPv4 and socket.SOCK_STREAM for TCP. Prints clear diagnostics on failure.
Connection
DNS Resolution & Connection
Resolves the target host and establishes a connection on port 80:
port = 80
host_ip = socket.gethostbyname("www.google.com")
s.connect((host_ip, port))
print(f"Successfully connected on port {port} and host ip addr is {host_ip}")
Captures gaierror for DNS failures and exits gracefully. Demonstrates real-world usage of gethostbyname and connect.
Learnings
Key Takeaways
- Basic socket API usage for TCP connections.
- DNS lookup handling with exception management.
- Connection establishment and status reporting.