I have a python network server code.
import socket
HOST, PORT = '', 5000
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_socket.bind((HOST, PORT))
listen_socket.listen(1)
print('Serving HTTP on port %s ...' % PORT)
while True:
client_connection, client_address = listen_socket.accept()
request = client_connection.recv(1024)
print(request)
http_response = """\
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
<H1>Hello, World!</H1>
"""
client_connection.sendall(http_response.encode())
client_connection.close()
I have a client code that accesses the server.
import socket
HOST = '127.0.0.1'
PORT = 5000 # The port used by the server
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket successfully created"
s.connect((HOST, PORT))
s.sendall('GET /')
data = s.recv(1000)
print('Received', repr(data))
s.close
except socket.error as err:
print "socket creation failed with error %s" %(err)
It works fine with the expected output when I executed the server and client.
Socket successfully created
('Received', "'HTTP/1.1 200 OK\\nContent-Type: text/html; charset=utf-8\\n\\n<H1>Hello, World!</H1>\\n'")
Then, I tried to execute the python server using ngrok.
Session Status online
Account ...
Version 2.3.34
Region United States (us)
Web Interface http://127.0.0.1:4040
Forwarding http://d2fccf7f.ngrok.io -> http://localhost:5000
Using curl
, I could access the webserver with ngrok.
> curl http://d2fccf7f.ngrok.io
<H1>Hello, World!</H1>
However, when I tried to use the same client code with minor modifications, the server doesn't seem to respond.
import socket
ip = socket.gethostbyname('d2fccf7f.ngrok.io')
print(ip)
HOST = ip
PORT = 5000
# the rest of the code is the same
I changed the PORT to 80 or 8080, but I had same results.
What might be wrong?
From oguz ismail's hint, I made the following REQUEST header to make it work. I see that the Host information and blank line should be required.
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket successfully created"
s.connect((HOST, PORT))
header = '''GET / HTTP/1.1\r\nHost: d2fccf7f.ngrok.io\r\n\r\n'''
...