Search code examples
pythonpython-3.xsocketsserverip-address

Failing to connect to a client/server with public IP address


I wish to exchange data between a server (for this purpose, I use a raspberry pi 3) and a pc as client on TWO DIFFERENT NETWORKS. However, I cannot connect the server and client when using the public ip addresses. Could it be something fire wall related (and in that case, how do I solve it?), or am I missing something fundamental?

I have not found any very helpful ways to do this yet. I have tried with the socket-library in python. When having the server and client on the same network, it works perfectly fine with the 192.168.x.x ip address format. Trying to adapt this to the case of two different networks, I have looked up the public ip address of the server/raspberry pi and replaced the 192.168.x.x ip address with it (this is what i gave seen people suggest). I have port forwarded the port 5000 to the raspberry pi on its network.

Server code:

import socket, time, os, random

class Server():
  def __init__(self,Adress=('',5000),MaxClient=1):
      self.s = socket.socket()
      self.s.bind(Adress)
      self.s.listen(MaxClient)
  def WaitForConnection(self):
      self.Client, self.Adr=(self.s.accept())
      print('Got a connection from: '+str(self.Client)+'.')


s = Server()
s.WaitForConnection()

Client code:

import socket

class Client():
   def __init__(self,Adress=("212.103.99.23",5000)):
      self.s = socket.socket()
      self.s.connect(Adress)

c = Client()

(the port number and public ip address are not the real ones for safety reasons, but I definitely put the correct ones when running the codes and port forwarded the corresponding port)


Solution

  • It is because of the mechanism of NAT.

    Consider the public IP you looked up (probably googled) is being shared with 100 other devices (you ISP manages this). How is your request to the server (to the public IP) is going to be routed to your server ?! Your request could belong to any of those 100 other devices.

    For solving your problem, your need to but a static IP (which may cost you money and time) or you can register a Domain-Name or other tricks (which I put a link about it down).

    https://security.stackexchange.com/questions/155159/how-to-directly-connect-to-devices-behind-nat-from-the-internet