Search code examples
pythontcpserverraspberry-pi

Python server TCP server accessable from anywhere (via external IP, port forwarding is done)


I am new here, so please, don't be angry if I am stupid - but I don't know about it. I would like to make a python TCP server, which can be accessed from anywhere via external (public) IP. I have done simple server (it works) in local network from this tutorial: https://www.youtube.com/watch?v=XiVVYfgDolU The client sends string and the server sends back that string but with uppercase.

Now I want to do the same but accessable from anywhere. I read a lot about it. I have Raspberry Pi, where I set up static IP address and I did the port forward (on port 42424). I am just looking for some tutorial, you can direct me anywhere - thats all I need. Or you can tell me how to do it step by step, but I know that it takes a lot of time to write answer. I tried googling, but I didn't find anything. And if I did, it was a person who didn't know what the external IP and the port forwarding is so the end of the conversation was: Learn what is port forwarding.

So please, give me some tips how to do it, or direct me somewhere. Thanks!

The code

Server:

import socket

def Main():
    host = '10.0.0.140'
    port = 42424
    s = socket.socket()
    s.bind((host, port))

    s.listen(1)
    c, addr = s.accept()
    while True:
        data = c.recv(1024)
        if not data:
            break
        data = str(data).upper()
        c.send(data)
    c.close()
if __name__ == '__main__':
    Main()

Client:

import socket

def Main():
    host = '10.0.0.140'
    port = 42424 
    s = socket.socket()
    s.connect((host,port))
    message = raw_input("->") 
    while message != 'q':
        s.send(message)
        data = s.recv(1024)
        message = raw_input("->")
    s.close()

if __name__ == '__main__':
    Main()

Solution

  • When connecting to a server behind a NAT firewall/router, in addition to port forwarding, the client should be directed to the IP address of the router. As far as the client is concerned, the IP address of the router is the server. The router simply forwards the traffic according to the port forwarding rules.