pythonsocketsnetwork-programmingtcpudp

Peer to peer socket communication without port forwarding


First of all I am not talking about a tcp or udp or socket implemented in a vps or server

My question is just like client to client socket communication.

Imagine listening at your home pc with a tcp socket. You can connect to this from home inter network anyway. But suppose someone wants to connect to it via the internet. Then you can create a forwarding rule on the router and bring it to working condition. Then the router knows that if an incoming connection comes from a port, the connection will be forwarded to the device in the relevant inter network. But the ISP I use does not support port forwarding.

I thought these were not impossible because of the team-viewer software. Because when I was connected to a friend in team-viewer, I opened the wire-shark and reviewed it. Then I saw that the data packet is exchanged peer to peer. Because the destination source addresses were my ip and friend's ip This means that the video data is exchanged without the participation of an additional server I highlighted the team-viewer connection. 61.245.175.81 is my friend's public IP. 192.168.1.130 is my internal IP

enter image description here

I want to do the same

Here is my simple socket code. This does not work through the internet because there is no router forwarding rule. I am very new to socket and networking side

Sever

import socket

server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(('', 12000))

while True:
    message, address = server_socket.recvfrom(1024)
    message = repr(message)
    print("Connected from ->  " + str(address) )
    print("Received data ->  " + message)
    reply = b"Hi from server :) "
    server_socket.sendto(reply, address)

Client

import time , datetime
import socket

client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client_socket.settimeout(1.0)

message = bytes(str(datetime.datetime.now()),'utf-8')
addr = ("192.168.1.130", 12000)

client_socket.sendto(message, addr)
try:
    data, server = client_socket.recvfrom(1024)
    print( repr(data) )
except: #socket.timeout:
    print('REQUEST TIMED OUT')

Can anyone give an explanation for my question


Solution

  • Pretty sure they do it using UDP hole punching, you'd need to do something similar to implement this.

    In a nutshell two clients behind NAT (which is what your router is doing) can use a third server acting as a sort of mediator to establish a connection.