chilliefiber
chilliefiber

Reputation: 651

Can't get python https socket to connect

So I have an apache web server installed on a vm. I want to write a simple script that will get the home page of the website using a socket. I was able to do it without ssl, but I recently installed ssl and thought I should try using the ssl version. This is the code I have, based off of another question Opening a SSL socket connection in Python

import socket, ssl
s = socket.socket()
wrappedSocket = ssl.wrap_socket(s)
wrappedSocket.connect(('127.0.0.1', 443))
wrappedSocket.sendall(
    'GET / HTTP/1.1\r\n'
    'Host: vulnerable\r\n'
    'User-Agent: sslsocket.py\r\n'
    'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n'
    'Accept-Language: en-US,en;q=0.5\r\n'
    'Accept-Encoding: gzip, deflate\r\n'
    'Connection: keep-alive\r\n'
    '\r\n'

)
ans = wrappedSocket.recv(4096)
print ans

The script keeps on running and never outputs anything. Upon further debugging, I found out it breaks on the connect() function call, but am unable to figure out why it happens.

Edit- After some help in the comments, I realised that the domain name is 127.0.1.1. However, now I get the HTTP headers as output, but it doesn't actually give me the HTML of the page. What is wrong this time?

Upvotes: 0

Views: 573

Answers (1)

David Jay Brady
David Jay Brady

Reputation: 1174

It seems liike you're really close, and Henrik has already addressed the issues about your connection.

If you are only recieving half of the message, it is probably due to the limit you put on recv. Try increasing that, or using the makefile method so you don't have to worry about the limit.

Edit: To show what makefile is and can do.

my_socket = socket.socket()
my_socket_input = my_socket.makefile('r')
my_socket_output = my_socket.makefile('w')

These new tools make doing things much simpler, as if you were writing and reading to a file. With your new socket_input variable, you can call methods like readline, and with socket_output, you can call methods like write.

some_text = my_socket_input.readline()

One of the details you don't need to worry about your is the buffer size on recv, as the makefile handles that for you

Upvotes: 2

Related Questions