Implementing an http server in python

Implementing an http server in python

Importing the Socket Module

Python
import socket
  • Importing Modules: Imports the socket module for working with sockets.

Creating and Configuring the Server Socket

Python
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mySocket.bind(('localhost', 8080))
  • Creating Socket: Creates a TCP socket using socket.AF_INET for IPv4 and socket.SOCK_STREAM for a stream-oriented connection (TCP).
  • Binding Socket: Binds the socket to the local address localhost and port 8080.

Listening for Incoming Connections

Python
mySocket.listen(5)
  • Listening: Configures the socket to listen for incoming connections with a backlog queue size of 5.

Handling Incoming Connections in a Loop

Python
while True:
    print('Waiting for connections')
    (recvSocket, address) = mySocket.accept()
  • Infinite Loop: Continuously waits for incoming connections.
  • Accepting Connection: Accepts an incoming connection, returning a new socket (recvSocket) and the address of the client.

Handling HTTP Request and Sending Response

Python
print('HTTP request received:')
print(recvSocket.recv(1024))
  • Receiving Data: Receives and prints the HTTP request data from the client (up to 1024 bytes).
Python
recvSocket.send(bytes("HTTP/1.1 200 OK\r\n\r\n <html><body><h1>Hello World!</h1></body></html> \r\n",'utf-8'))
  • Sending Response: Sends an HTTP response to the client indicating a successful status (200 OK) and a simple HTML page.

Closing the Connection

Python
recvSocket.close()
  • Closing Connection: Closes the socket for the individual connection.
Python
import socket

mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mySocket.bind(('localhost', 8080))

mySocket.listen(5)

while True:
    print('Waiting for connections')
    (recvSocket, address) = mySocket.accept()
    print('HTTP request received:')
    print(recvSocket.recv(1024))
    recvSocket.send(bytes("HTTP/1.1 200 OK\r\n\r\n <html><body><h1>Hello World!</h1></body></html> \r\n",'utf-8'))
    recvSocket.close()

This script represents a simple HTTP server that listens on localhost:8080. It accepts incoming connections, prints received HTTP requests, sends a basic HTML response, and then closes the connection. Note that this example is minimal and may not handle all aspects of a production-level HTTP server. It’s mainly intended for educational purposes.

Implementing a basic HTTP server in Python can be done using the built-in http.server module. Below is a simple example of how you can create an HTTP server that serves static files from the current directory.

Python
import http.server
import socketserver

# Set the port number
port = 8080

# Choose the handler you want to use
handler = http.server.SimpleHTTPRequestHandler

# Create the server with the specified handler
with socketserver.TCPServer(("", port), handler) as httpd:
    print(f"Serving on port {port}")
    # Start the server
    httpd.serve_forever()

Here’s a breakdown of the code:

  1. Import Necessary Modules:
    • http.server: Provides basic HTTP server classes.
    • socketserver: Allows the creation of network servers.
  2. Set the Port Number:
    • Define the port on which the server will listen. In this case, it’s set to 8080.
  3. Choose the Handler:
    • Use http.server.SimpleHTTPRequestHandler as the handler. This handler serves files from the current directory and its subdirectories.
  4. Create and Start the Server:
    • Use socketserver.TCPServer to create a TCP server, specifying the host (“” means all available interfaces) and the port.
    • The with statement ensures that the server is properly closed when the script exits.
    • Print a message indicating that the server is running.
    • Call httpd.serve_forever() to start serving requests indefinitely.

Save this code in a file (e.g., http_server.py) and run it using:

Bash
python http_server.py

Your basic HTTP server will be accessible at http://localhost:8080, and you can navigate to different files and directories within the current directory. This example is suitable for serving static files during development, and for production, you may consider more advanced frameworks like Flask or Django.

Testing the HTTP Server

Shebang and Importing the Socket Module

Python
#!/usr/bin/python
import socket
  • Shebang and Import: Specifies the shebang line to indicate the Python interpreter to be used. Imports the socket module for working with sockets.

Setting Web Host and Port

Python
webhost = 'localhost'
webport = 8080
  • Setting Web Host and Port: Defines the target web host (localhost) and port (8080) to connect to.

Connecting to the Web Server

Python
print("Contacting %s on port %d ..." % (webhost, webport))
webclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
webclient.connect((webhost, webport))
  • Connection Setup: Prints a message indicating the target host and port. Creates a TCP socket (webclient) using socket.AF_INET for IPv4 and socket.SOCK_STREAM for a stream-oriented connection (TCP). Connects to the specified web host and port.

Sending an HTTP GET Request

Python
webclient.send(bytes("GET / HTTP/1.1\r\nHost: localhost\r\n\r\n".encode('utf-8')))
  • Sending Request: Sends an HTTP GET request to the web server. The request includes the HTTP version, the requested resource (“/”), and the “Host” header.

Receiving and Printing the Server’s Response

Python
reply = webclient.recv(4096)
print("Response from %s:" % webhost)
print(reply.decode())
  • Receiving Response: Receives the server’s response, up to 4096 bytes, and stores it in the reply variable.
  • Printing Response: Prints the response from the web server, decoding it from bytes to a UTF-8 string.

Closing the Socket

Python
webclient.close()
  • Closing Connection: Closes the socket after the communication with the web server is complete.
Python
#!/usr/bin/python
import socket
webhost = 'localhost'
webport = 8080
print("Contacting %s on port %d ..." % (webhost, webport))
webclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
webclient.connect((webhost, webport))
webclient.send(bytes("GET / HTTP/1.1\r\nHost: localhost\r\n\r\n".encode('utf-8')))
reply = webclient.recv(4096)
print("Response from %s:" % webhost)
print(reply.decode())

This script acts as a simple HTTP client that connects to a web server (localhost:8080 in this case), sends an HTTP GET request, receives the server’s response, and prints it. Note that this example is minimal and may not handle all aspects of a production-level HTTP client. It’s mainly intended for educational purposes.

Total
3
Shares

Leave a Reply

Previous Post
Setting basic client with the socket module

Setting basic client with the socket module

Next Post
Implementing a reverse shell with sockets

Implementing a reverse shell with sockets

Related Posts