'Python Socket to connect over Global Public IP Address

I have been working on a project to connect computers located in different locations together through Python. Initially, while testing, I used my private IP address (I did not know it was private at the time) to connect computers on the same network as mine. But as soon as I tried doing this with computers located on different networks in different locations, it simply did not work.

And I assume this is because the program is using the local IP address of my computer that can connect only to computers on the same network. Here are my simplified programs:

Here is my server-side script:

server = socket.gethostbyname(socket.gethostname()) # 10.128.X.XXX which is the Internal IP
print(server)
port = 5555
clients = 0

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((server, port))

s.listen(2)
print("Waiting for connection...")

while True:
    conn, addr = s.accept()
    print("Connected to: ", addr)

    conn.send(str.encode(f"{clients}"))
    clients += 1

and here is my client side-script:

class Network:
    def __init__(self):
        self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server = "10.128.0.2"
        self.port = 5555
        self.addr = (self.server, self.port)
        self.id = int(self.connect())

    def connect(self):
        self.client.connect(self.addr)
        return self.client.recv(2048).decode()

network = Network()
print(f"Connected as client {network.id}")

Now when I tried replacing the private IP address with the global IP address (as specified here: How do I get the external IP of a socket in Python?) I got the following error:

# Getting the Global IP Address

from requests import get
server = get("https://api.ipify.org").text
s.bind((server, port))
OSError: [WinError 10049] The requested address is not valid in its context

I have tried searching a lot on how to communicate (transfer small amounts of data as strings) between multiple computers located in different locations using different networks, but I haven't really gotten a solution. Is there a way that I can do this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source