-
Notifications
You must be signed in to change notification settings - Fork 9
/
udp_proxy.py
executable file
·62 lines (49 loc) · 1.68 KB
/
udp_proxy.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
62
#! /usr/bin/env python
# coding: utf-8
from optparse import OptionParser
import socket
import logging
logger = logging.getLogger()
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)
def parse_args():
parser = OptionParser()
parser.add_option('--bind-address',
help='The address to bind, use 0.0.0.0 for all ip address.')
parser.add_option('--port',
help='The port to listen, eg. 623.',
type=int)
parser.add_option('--dst-ip',
help='Destination host ip, eg. 192.168.3.101.')
parser.add_option('--dst-port',
help='Destination host port, eg. 623.',
type=int)
return parser.parse_args()
(options, args) = parse_args()
def recv():
sock_src = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock_dst = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
recv_addr = (options.bind_address, options.port)
dst_addr = (options.dst_ip, options.dst_port)
sock_src.bind(recv_addr)
while True:
data, addr = sock_src.recvfrom(65565)
if not data:
logger.error('an error occured')
break
logger.debug('received: {0!r} from {1}'.format(data, addr))
sock_dst.sendto(data, dst_addr)
data, _ = sock_dst.recvfrom(65565)
sock_src.sendto(data, addr)
sock_src.close()
sock_dst.close()
if __name__ == '__main__':
parse_args()
try:
recv()
except KeyboardInterrupt:
exit(0)