-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.py
More file actions
67 lines (57 loc) · 1.59 KB
/
server.py
File metadata and controls
67 lines (57 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/env python
#
# Proof of Concept: UDP Hole Punching
# Two client connect to a server and get redirected to each other.
#
# This is the rendezvous server.
#
# Koen Bollen <meneer koenbollen nl>
# 2010 GPL
#
import socket
import struct
import sys
def addr2bytes( addr ):
"""Convert an address pair to a hash."""
host, port = addr
try:
host = socket.gethostbyname( host )
except (socket.gaierror, socket.error):
raise ValueError, "invalid host"
try:
port = int(port)
except ValueError:
raise ValueError, "invalid port"
bytes = socket.inet_aton( host )
bytes += struct.pack( "H", port )
return bytes
def main():
port = 4653
try:
port = int(sys.argv[1])
except (IndexError, ValueError):
pass
sockfd = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
sockfd.bind( ("", port) )
print "listening on *:%d (udp)" % port
poolqueue = {}
while True:
data, addr = sockfd.recvfrom(32)
print "connection from %s:%d" % addr
pool = data.strip()
sockfd.sendto( "ok "+pool, addr )
data, addr = sockfd.recvfrom(2)
if data != "ok":
continue
print "request received for pool:", pool
try:
a, b = poolqueue[pool], addr
sockfd.sendto( addr2bytes(a), b )
sockfd.sendto( addr2bytes(b), a )
print "linked", pool
del poolqueue[pool]
except KeyError:
poolqueue[pool] = addr
if __name__ == "__main__":
main()
# vim: expandtab shiftwidth=4 softtabstop=4 textwidth=79: