Search code examples
pythontcp

How to send data between two Raspberry Pis in two separate houses using TCP


So I'm trying to figure out how to send string data between two Pi Zero W units. I want one of them to be with me and one of them to be with one of my friends in her house. I'm really confused as to how this would work. I found a bit of code that seemed to work for both units in my house but, after changing the IP Address to my friend's public IP and trying to use it at her house, nothing came through. I'm fairly new to using internet protocols so any help would be appreciated.

Send.py

import sys
from socket import socket, AF_INET, SOCK_DGRAM

SERVER_IP   = ''
PORT_NUMBER = 5000
SIZE = 1024
print ("Test client sending packets to IP {0}, via port 
{1}\n".format(SERVER_IP, 
PORT_NUMBER))

mySocket = socket( AF_INET, SOCK_DGRAM )

while True:
    myMessage = input()
    mySocket.sendto(myMessage.encode('utf-8'),(SERVER_IP,PORT_NUMBER))
sys.exit()

Receive.py

#!/usr/bin/env python3

from socket import socket, gethostbyname, AF_INET, SOCK_DGRAM
import sys
PORT_NUMBER = 5000
SIZE = 128

hostName = gethostbyname( '0.0.0.0' )

mySocket = socket( AF_INET, SOCK_DGRAM )
mySocket.bind( (hostName, PORT_NUMBER) )

print ("Test server listening on port {0}\n".format(PORT_NUMBER))

while True:
    (data,addr) = mySocket.recvfrom(SIZE)
    print(data.decode('utf-8'))
sys.exit()

Solution

  • if you want to connect them together:

    1. RPI that listens to incoming TCP connections (Receive.py) has to have firewall port open on RPI (https://raspberrypi.stackexchange.com/questions/69123/how-to-open-a-port)
    2. there has to be port open on your home router that connects your RPI to the ISP
    3. your RPI cannot be behind provider's NAT network - sometimes, you can purchase a static IP address from your provider, that doesn't change or at least public IP address that dynamically changes in time.

    You can check if you're behind NAT in router admin page, check if the IP that router got assigned from ISP is the same as your IP address that servers on the internet see. Do this query:

    https://www.google.com/search?q=what+is+my+ip+address )

    If they're same, you're not behind ISP's NAT and problem is not probably there. If the're different, you share IP's with other ISP's customers and you cannot run your own server app that will expose it's port to the internet.