1

I am sending a get request to any host using sockets tcp, but I keep on getting "301 Moved Permanently" from pages with https.

I have tried to do it by changing the port from 80 to 443.

I have tried with the ssl library as well.

But keep getting 301 code

This is the code

import socket
import click
@click.command()
@click.option("-h", "--host", prompt=True)
@click.option("-p", "--port", type=int, prompt=True, default=80)
def cli(host, port):

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)                                 
    sock.connect((host, port))                       

    message = f"GET / HTTP/1.1\r\nHost:{host}\r\nConnection: close\r\n\r\n"
    request = message.encode('utf-8')
    sent = 0

    while sent < len(request):
        sent = sent + sock.send(request[sent:])
    response = b""

    while True:
        chunk = sock.recv(4096)
        if len(chunk) == 0: # If no more data received, quitting
            break
    response = response + chunk

    response_decode = response.decode('latin-1') 

    sock.close()          

    print(response_decode)

This is the response when I try to connect to www.eltiempo.com by port 80

HTTP/1.1 301 Moved Permanently
Server: AkamaiGHost
Content-Length: 0
Location: https://www.eltiempo.com/
Cache-Control: max-age=120
Expires: Sat, 12 Feb 2022 18:24:28 GMT
Date: Sat, 12 Feb 2022 18:22:28 GMT
Connection: close
Server-Timing: cdn-cache; desc=HIT
Server-Timing: edge; dur=1
version: desktop

I get this error with port 443

chunk = sock.recv(4096)
ConnectionResetError: [Errno 104] Connection reset by peer

Please tell me how to improve my code to avoid this 301 code.

TheBened
  • 11
  • 1

0 Answers0