-
Notifications
You must be signed in to change notification settings - Fork 2
/
nat.py
61 lines (53 loc) · 1.62 KB
/
nat.py
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
#!/usr/bin/env python3
def nat_traversal():
from socket import socket, AF_INET, SOCK_DGRAM, timeout
import stun
import json
import os
import sys
import subprocess
import time
LPORT = 65000
LHOST = '0.0.0.0'
nat = stun.get_ip_info(LHOST, LPORT)
nat_json = json.dumps(nat)
os.system("clear")
os.system(f"echo '{nat_json}' | qrencode -t ansiutf8")
print(f"Your host parameters: {nat}")
# clean clipboard
os.system("termux-clipboard-set '' ")
# try to get remote nat info in one minute
print("Please, copy remote host info to your clipboard ...")
remote_nat = ''
for i in range(12):
cb = subprocess.getoutput('termux-clipboard-get')
try:
remote_nat = json.loads(cb)
if remote_nat:
break
except json.decoder.JSONDecodeError:
pass
time.sleep(5)
else:
print("Error: can't get remote host info", file=sys.stderr)
sys.exit(1)
print(f"Got remote host parameters: {remote_nat}")
fnat_type, rip, rport = remote_nat
sock = socket(AF_INET, SOCK_DGRAM)
sock.bind((LHOST, LPORT))
sock.settimeout(5)
for i in range(12):
try:
sock.sendto(b'NAT\n', (rip, rport))
sock.recv(1024)
except timeout:
pass
else:
sock.sendto(b'NAT\n', (rip, rport))
break
else:
print(f"Error: can't connect to remote host {rip}:{rport}", file=sys.stderr)
sys.exit(1)
print(f"Connection established with {rip}:{rport}")
sock.settimeout(None)
return rip, rport, sock