SocketProgramming

← Back to Toolkit

Project Overview

Demonstrates basic TCP socket creation, DNS resolution, and server connection using Python's socket module, with robust error handling.

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.

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.

Key Takeaways

View Full Code on GitHub