pythonpython-sockets

How to send messages to a remote computer using python socket module?


I'm trying to send a message from a computer to a another computer that is not connected to the other computer local network. I did port forwarding (port 8080, TCP) and I didn't manage to get the remote computer to connect and to send the message. when i try to connect it's just getting stuck on the connect method (client).

I also need to mention that I'm open to change anything in the router settings.

the client code (remote computer):

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("%My public IP address%", 8080))
msg = s.recv(1024)
msg = msg.decode("utf-8")
print(msg)

the server code:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("192.168.0.2", 8080))
s.listen(5)

while True:
   clientsocket, address = s.accept()
   print(f"Connection from {address} has been established.")
   clientsocket.send(bytes("Hey there!!", "utf-8"))
   clientsocket.close()

Solution

  • From my understanding, your aim is to connect to a server from a remote computer and send a message from the server to the client. As such, all it requires is the client to connect to the external-facing IP address of your server. Once that is done, router simply forwards the traffic according to the port forwarding rules.

    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' #The host on your client needs to be the external-facing IP address of your router. Obtain it from here https://www.whatismyip.com/
        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()
    

    Also do note that, 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.