0

I'm trying use the python socket module to connect to an ngrok server. If I put the ngrok into my browser it connects properly so the problem is somewhere with my client code. Here is the server code:

#server.py
import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
    def handle(self):
        self.data = self.request.recv(1024).strip()
        print("{} wrote:".format(self.client_address[0]))
        print(self.data)
if __name__ == "__main__":
    HOST, PORT = "192.168.86.43", 8080
    server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
    server.serve_forever()

And here is the client:

#client.py
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    sock.connect(("http://urlhere.ngrok.io", 8080))
    sock.sendall(bytes("Hello" + "\n", "utf-8"))

Thanks!

Tanuj KS
  • 155
  • 2
  • 14

1 Answers1

0

In general you should be able to connect to any globally available address or DNS name, ensuring there is no network restrictions on the way. However you have to listen on the address that is locally available for global routing if you are communicating across the Internet.

As for particular code, there are 2 issues:

  1. Socket should be connected to an address or DNS name. The protocol is defined with the socket type. In your case
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    sock.connect(("localhost", 8080))
    sock.sendall(bytes("Hello" + "\n", "utf-8"))
  1. You're binding in the server to some speciffic not related address. To run your code you should bind to either localhost or to "any available" address "0.0.0.0":
import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
    def handle(self):
        self.data = self.request.recv(1024).strip()
        print("{} wrote:".format(self.client_address[0]))
        print(self.data)
if __name__ == "__main__":
    HOST, PORT = "0.0.0.0", 8080
    server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
    server.serve_forever()
Robert Navado
  • 1,319
  • 11
  • 14
  • I want to be able to connect even if I'm not on the same network, is this possible with your method? – Tanuj KS Oct 29 '20 at 17:47
  • Also the IP is not the issue, if I run connect to 192.168.86.43 it works but I want to be able to connect to the ngrok that forwards to 192.168.86.43 – Tanuj KS Oct 29 '20 at 17:49
  • 1
    @TanujKS: You can specify the DNS name in the `connect()` call, you just can't use the URL form. Thus `sock.connect(("urlhere.ngrok.io", 8080))` should connect. – President James K. Polk Oct 29 '20 at 21:53
  • Yes. You can connect to any globally available address or DNS name, ensuring there is no network restrictions on the way. However you have to listen on the address that is locally available for global routing if your're communicating across the Internet. – Robert Navado Oct 30 '20 at 14:58