Vifibnet now establish a few random connection from a list a given peers and change...
[re6stnet.git] / upnpigd.py
1 import miniupnpc
2 import socket
3
4 # return (address, port)
5 def ForwardViaUPnP(localPort):
6 u = miniupnpc.UPnP()
7 u.discoverdelay = 200
8 u.discover()
9 u.selectigd()
10 externalPort = 1194
11 while True:
12 while u.getspecificportmapping(externalPort, 'TCP') != None:
13 externalPort = max(externalPort + 1, 49152)
14 if externalPort == 65536:
15 raise Exception
16 if u.addportmapping(externalPort, 'UDP', u.lanaddr, localPort, 'Vifib openvpn server', ''):
17 return (u.externalipaddress(), externalPort)
18
19 # TODO : specify a lease duration
20 # TODO : use more precises exceptions
21 # TODO : be sure that GetLocalIp do not bug
22
23 def GetLocalIp():
24 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
25 s.connect(('10.8.8.8', 0))
26 return s.getsockname()[0]
27
28
29 def GetExternalInfo(localPort):
30 try:
31 return ForwardViaUPnP(localPort)
32 except Exception:
33 return (GetLocalIp(), localPort)
34