Udp hole punching python

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

vkirovskiy/p2ptool

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

This script demonstrates how to connect using UDP hole punching.

This script is a part of p2p service that uses UDP to connect to other clients.

Script requires server udphelper.lua runned on somewhere in internet. Server helps clients to find each other by sending them its real ip addressed and ports. Then clients need to use UDP Hole Punching method to connect.

udphepler.lua must runs on server with real IP but clients do not require it and can run behind firewall with NAT.

usage: p2ptool.py [-h] [--myid MYID] [-p P] [--connect CONNECT] [--wait WAIT] [-v] server positional arguments: server helper server ip optional arguments: -h, --help show this help message and exit --myid id id to find you -p Port server port --connect id auto connect to --wait id wait client and exit -v verbose mode 

./p2ptool.py —myid first-client-id -p 8001 —connect second-client-id helper-server-ip

./p2ptool.py —myid second-client-id -p 8001 —wait first-client-id helper-server-ip

Читайте также:  Питон дружит с мальчиком

When UDP hole was panched all clients will finish:

  • first client will return: id, client address, client port, your src port
  • second client will return: id, own local address, own src port

Then you can use any other software that uses udp exchange.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

UDP hole punching server and client implementation with twisted in python.

stylesuxx/udp-hole-punching

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

UDP hole punching server and client implementation with twisted in python.

All systems where either client or server are running need to have python 2.7 installed. Further the twisted networking engine is required.

The server needs to run on a system with a public reachable IP.

The clients need to run on two separate hosts behind (at least one) NAT, like for example a home router.

The server is used by the clients to exchange connection details. The public IP address and port of the server is known by both clients.

Clients connect to the rendezvous server and wait for connection details about another peer to be transmitted by the server. Once this is done, they initialize a connection with each other and start exchanging messages.

Usage: ./client.py RENDEZVOUS_IP RENDEZVOUS_PORT 

After starting the server and both clients you should see the following output when hole punching worked between the two peers:

Listening on *:9999 Registration from xxx.109.xxx.90:43242 Registration from 184.xxx.19.xxx:59019 Linked peers 
Connected to server, waiting for peer. Sent init to 184.xxx.19.xxx:59019 Received: Message from 0.0.0.0:59019 
Connected to server, waiting for peer. Sent init to 80.109.103.90:43242 Received: Message from 0.0.0.0:43242 

About

UDP hole punching server and client implementation with twisted in python.

Читайте также:  JavaScript get local IP address

Источник

Udp hole punching python

Set up an intermediate server 111.222.111.2222 on the public network

from socket import * import threading server_addr = ('111.222.111.2222',6000) udpSerSock = socket(AF_INET,SOCK_DGRAM) udpSerSock.bind(server_addr) hostDict=> #Save logged in client def revMsg(): print("start rev:") while True: data, address = udpSerSock.recvfrom(1024) try: (msg_type,msg_hostname,msg_contain)=str(data).split('|') except: print('[error msg!]', str(data)) continue # Respond according to the type of message if int(msg_type)==9:#Save connection udpSerSock.sendto('%d|%s|%s' % (9,"Server","keep live"), address) elif int(msg_type)==0:#Register client ip and port hostDict[msg_hostname]="%s:%s" % (address[0],address[1]) print('[login: %s:%s]:%s' % (address[0],address[1],msg_hostname)) udpSerSock.sendto('%d|%s|%s' % (0,address[0],address[1]), address) elif int(msg_type)==1:#Return to online client information print('[query: %s]' % (msg_hostname)) udpSerSock.sendto('%d|%s|%s' % (1,str(hostDict)," "), address) elif int(msg_type)==2:#p2pConnect to the specified client online_list=hostDict.keys() if msg_hostname in online_list: item=hostDict[msg_hostname] (B_ip,B_port)=item.split(':') print('[%s connect to :%s]' % (address[0],B_ip)) udpSerSock.sendto('%d|%s|%s' % (2,B_ip,B_port), address) # Notify the specified client to respond to the p2p connection print('[Remind B]') udpSerSock.sendto('%d|%s|%s' % (4,address[0],address[1]), (B_ip,int(B_port))) else:#Specify the client does not exist print('[B offline]') udpSerSock.sendto('%d|%s|%s' % (3,"0","0"), address) #Start listening for messages try: thread = threading.Thread(target = revMsg) thread.setDaemon(True) thread.start() except: print "Error: unable to start thread" #Accept input while True: msg = raw_input(">>") if str(msg).strip()=='exit': print("exit!") break # udpSerSock.sendto(msg, address) udpSerSock.close() 
import socket import threading import time server_addr = ('111.222.111.2222', 6000) udpSerSock= socket.socket(socket.AF_INET, socket.SOCK_DGRAM) Clinet_Name="clinet_A" def heartbeat(): while True: udpSerSock.sendto('%d|%s|%s' % (9,"keep ","live"), server_addr) time.sleep(10) def revMsg(): global peer_ip,peer_port print(" start rev:") while True: data, addr = udpSerSock.recvfrom(1024) try: (msg_type,msg_arg1,msg_arg2)=str(data).split('|') except: print('[error msg!]', str(data)) continue if int(msg_type)==9: continue elif int(msg_type)==0: print('[login success: %s]' % (str(data))) elif int(msg_type)==1: print("online hosts:\n%s"% (msg_arg1)) elif int(msg_type)==2: print('[peer online]') peer_ip=msg_arg1 peer_port=msg_arg2 elif int(msg_type)==3: print('[peer offline]') elif int(msg_type)==4: print('[respond peer]') udpSerSock.sendto('%d|%s|%s' % (9,"hello"," "), (msg_arg1,int(msg_arg2))) elif int(msg_type)==5: print('[peer msg]:%s'% msg_arg1) else: print('[error Type!]', str(data)) try: rev_thread = threading.Thread(target = revMsg) rev_thread.setDaemon(True) rev_thread.start() heat_thread=threading.Thread(target = heartbeat) heat_thread.setDaemon(True) heat_thread.start() except: print "Error: unable to start thread" # ======================== host_name="Noname" # Execute the 0, 1, 2, 3 commands in turn to complete the p2p connection and chat directly while True: comd = raw_input("Commend[0,1,2,3]>>") # query online host if str(comd).strip()=='0': host_name = raw_input("hostname>>") udpSerSock.sendto('%d|%s|%s' % (0,str(host_name).strip()," "), server_addr) elif str(comd).strip()=='1': print("get online host. ") udpSerSock.sendto('%d|%s|%s' % (1," "," "), server_addr) elif str(comd).strip()=='2': peer_name = raw_input("peer_name>>") print("get peer ip. ") udpSerSock.sendto('%d|%s|%s' % (2,str(peer_name).strip()," "), server_addr) elif str(comd).strip()=='3': msg = raw_input("Msg>>") udpSerSock.sendto('%d|%s|%s' % (5,str(msg).strip()," "), (peer_ip,int(peer_port))) if str(comd).strip()=='exit': print("exit!") break udpSerSock.close() 

Источник

tnytown / udp_hole_punch_tester.py

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

#!/usr/bin/env python
#
# udp_hole_punch_tester.py — UDP Hole Punching test tool
#
# Usage: udp_hole_punch_tester.py remote_host remote_port
#
# Run this script simultaneously on 2 hosts to test if they can punch
# a UDP hole to each other.
#
# * remote_port should be identical on 2 hosts.
# * if remote_port < 1024, must be root.
# * tested on python 2.5.
#
# Copyright (C) 2009 Dmitriy Samovskiy, http://somic.org
#
# License: Apache License, Version 2.0
# http://www.apache.org/licenses/
#
import sys , os , time , socket , random , struct
from select import select
def log ( * args ):
print ( time . asctime (), ‘ ‘ . join ([ str ( x ) for x in args ]))
def puncher ( remote_host , port ):
sock = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM )
sock . bind (( » , port ))
my_token = struct . pack ( ‘f’ , random . random ())
log ( «my_token =» , my_token )
remote_token = b»_»
sock . setblocking ( 0 )
sock . settimeout ( 5 )
remote_knows_our_token = False
for i in range ( 60 ):
r , w , x = select ([ sock ], [ sock ], [], 0 )
if remote_token != «_» and remote_knows_our_token :
log ( «we are done — hole was punched from both ends» )
break
if r :
data , addr = sock . recvfrom ( 1024 )
log ( «recv:» , data )
if remote_token == «_» :
remote_token = data . split ()[ 0 ]
log ( «remote_token is now» , remote_token )
if len ( data . split ()) == 3 :
log ( «remote end signals it knows our token» )
remote_knows_our_token = True
if w :
data = b»%s %s» % ( my_token , remote_token )
if remote_token != «_» : data += b» ok»
log ( «sending:» , data )
sock . sendto ( data , ( remote_host , port ))
log ( «sent» , i )
time . sleep ( 0.5 )
log ( «done» )
sock . close ()
return remote_token != «_»
if __name__ == ‘__main__’ :
remote_host = sys . argv [ 1 ]
port = int ( sys . argv [ 2 ])
if puncher ( remote_host , port ):
log ( «Punched UDP hole to %s:%d successfully» % ( remote_host , port ))
else :
log ( «Failed to punch hole» )

Источник

Оцените статью