How to respond to a GET request for favicon.ico in a local webserver using sockets

Viewed 409

I have created my own webserver using python and its built-in module sockets, now when I run the code the browser asks for favicon.ico earlier I was silencing it but now I decided to give a favicon.ico file to the browser but it doesn't seem to be working

server.py

...
SERVER_HOST = '0.0.0.0'
SERVER_PORT = 8000


server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((SERVER_HOST, SERVER_PORT))
server_socket.listen(1)
...
while True:
    client_connection, client_address = server_socket.accept()
    request = client_connection.recv(1024).decode()
    ...

    response = 'HTTP/1.1 200 OK\r\n'
    # the code here is a little bit clustered, I will fix it when I solve this favicon problem
    if filename == '/':
        filename = '/index.html'
    if filename != "/favicon.ico":
        response += "Content-Type: text/html\r\n"
        with open(f"htdocs/{filename}") as f:
            data = f.read()
        response += f"Content-Length: {len(data)}\r\n\r\n{data}"
        client_connection.sendall(response.encode())
    else:
        with open(f"htdocs/{filename}", "rb") as f:
            data = f.read()
        response += f"Content-Type: image/x-icon\r\nContent-Length: {len(data)}\r\n\r\n"
        response += (base64.b64encode(data)).decode('utf-8')
        client_connection.sendall(response.encode())
    client_connection.close()

Folder Structure

/Webserver$ ls
htdocs  server.py  venv
/Webserver$ ls htdocs
favicon.ico  home.html  index.html

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
      <meta charset="UTF-8">
      <title>Index</title>
      <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon"/>
  </head>
  <body>
    <h1>Hello World!</h1>
    <p>Welcome to the index.html web page..</p>
    <p>Here's a link to <a href="home.html">home</a></p>
  </body>
</html>

enter image description here here the favicon.ico is even sent as image/x-icon but it is not displyed.

The htdocs/favicon.ico has dimensions 16x16

enter image description here

0 Answers
Related