Python UDP 服务器未接收数据
Python UDP Server Not Receiving Data
我想在一台机器 (192.168.2.2:7800) 上接收 UDP 以太网流量(来自另一台机器 (192.168.2.12))。
我可以通过 tcp 转储看到数据在接收机器上流动:
tcpdump -n -i enp5s0f1 udp port 7800
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on enp5s0f1, link-type EN10MB (Ethernet), capture size 262144 bytes
19:04:13.160763 IP 192.168.2.12.ovbus > 192.168.2.2.asr: UDP, length 1052
19:04:13.170854 IP 192.168.2.12.ovbus > 192.168.2.2.asr: UDP, length 1052
我已经尝试使用我从 Radoslaw Matusiak here (https://github.com/rsc-dev/pyproxy/blob/master/code/pyproxy.py) 获得的以下代码设置 IP 为 192.168.2.2 和端口为 7800 的 python UDP 服务器:
#!/usr/bin/env python
__author__ = 'Radoslaw Matusiak'
__copyright__ = 'Copyright (c) 2016 Radoslaw Matusiak'
__license__ = 'MIT'
__version__ = '0.1'
"""
TCP/UDP proxy.
"""
import argparse
import signal
import logging
import select
import socket
FORMAT = '%(asctime)-15s %(levelname)-10s %(message)s'
logging.basicConfig(format=FORMAT)
LOGGER = logging.getLogger()
LOCAL_DATA_HANDLER = lambda x:x
REMOTE_DATA_HANDLER = lambda x:x
BUFFER_SIZE = 2 ** 10 # 1024. Keep buffer size as power of 2.
def udp_proxy(src, dst):
"""Run UDP proxy.
Arguments:
src -- Source IP address and port string. I.e.: '127.0.0.1:8000'
dst -- Destination IP address and port. I.e.: '127.0.0.1:8888'
"""
LOGGER.debug('Starting UDP proxy...')
LOGGER.debug('Src: {}'.format(src))
LOGGER.debug('Dst: {}'.format(dst))
proxy_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
proxy_socket.bind(ip_to_tuple(src))
client_address = None
server_address = ip_to_tuple(dst)
LOGGER.debug('Looping proxy (press Ctrl-Break to stop)...')
while True:
data, address = proxy_socket.recvfrom(BUFFER_SIZE)
LOGGER.debug('Data Received')
if client_address == None:
client_address = address
if address == client_address:
data = LOCAL_DATA_HANDLER(data)
proxy_socket.sendto(data, server_address)
elif address == server_address:
data = REMOTE_DATA_HANDLER(data)
proxy_socket.sendto(data, client_address)
client_address = None
else:
LOGGER.warning('Unknown address: {}'.format(str(address)))
# end-of-function udp_proxy
def tcp_proxy(src, dst):
"""Run TCP proxy.
Arguments:
src -- Source IP address and port string. I.e.: '127.0.0.1:8000'
dst -- Destination IP address and port. I.e.: '127.0.0.1:8888'
"""
LOGGER.debug('Starting TCP proxy...')
LOGGER.debug('Src: {}'.format(src))
LOGGER.debug('Dst: {}'.format(dst))
sockets = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(ip_to_tuple(src))
s.listen(1)
s_src, _ = s.accept()
s_dst = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s_dst.connect(ip_to_tuple(dst))
sockets.append(s_src)
sockets.append(s_dst)
while True:
s_read, _, _ = select.select(sockets, [], [])
for s in s_read:
data = s.recv(BUFFER_SIZE)
if s == s_src:
d = LOCAL_DATA_HANDLER(data)
s_dst.sendall(d)
elif s == s_dst:
d = REMOTE_DATA_HANDLER(data)
s_src.sendall(d)
# end-of-function tcp_proxy
def ip_to_tuple(ip):
"""Parse IP string and return (ip, port) tuple.
Arguments:
ip -- IP address:port string. I.e.: '127.0.0.1:8000'.
"""
ip, port = ip.split(':')
return (ip, int(port))
# end-of-function ip_to_tuple
def main():
"""Main method."""
parser = argparse.ArgumentParser(description='TCP/UPD proxy.')
# TCP UPD groups
proto_group = parser.add_mutually_exclusive_group(required=True)
proto_group.add_argument('--tcp', action='store_true', help='TCP proxy')
proto_group.add_argument('--udp', action='store_true', help='UDP proxy')
parser.add_argument('-s', '--src', required=True, help='Source IP and port, i.e.: 127.0.0.1:8000')
parser.add_argument('-d', '--dst', required=True, help='Destination IP and port, i.e.: 127.0.0.1:8888')
output_group = parser.add_mutually_exclusive_group()
output_group.add_argument('-q', '--quiet', action='store_true', help='Be quiet')
output_group.add_argument('-v', '--verbose', action='store_true', help='Be loud')
args = parser.parse_args()
if args.quiet:
LOGGER.setLevel(logging.CRITICAL)
if args.verbose:
LOGGER.setLevel(logging.NOTSET)
if args.udp:
udp_proxy(args.src, args.dst)
elif args.tcp:
tcp_proxy(args.src, args.dst)
# end-of-function main
if __name__ == '__main__':
main()
然而,当我 运行 命令 testpyProxy.py --udp -d 192.168.2.13:7800 -s 192.168.2.2:7800 我从来没有收到:
2009-01-23 19:11:38,786 DEBUG BUFFER SIZE: 32768
2009-01-23 19:11:38,786 DEBUG Starting UDP proxy...
2009-01-23 19:11:38,786 DEBUG Src: 192.168.2.2:7800
2009-01-23 19:11:38,786 DEBUG Dst: 192.168.2.12:7800
2009-01-23 19:11:38,787 DEBUG Looping proxy (press Ctrl-Break to stop)...
此 python 代理 运行 在 Centos 7 (192.168.2.2) 机器上使用来自 ifconfig 的以太网端口连接统计信息:
enp5s0f1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 9000
inet 192.168.2.2 netmask 255.255.255.0 broadcast 192.168.2.255
inet6 fe80::21b:acff:fe02:af29 prefixlen 64 scopeid 0x20<link>
ether 00:1b:ac:02:af:29 txqueuelen 1000 (Ethernet)
RX packets 206136919 bytes 494683048962 (460.7 GiB)
RX errors 0 dropped 50795 overruns 0 frame 0
TX packets 1018446 bytes 564508158 (538.3 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
非常感谢任何帮助。
更新:
感谢 tdelaney 的建议,我已经 运行ning 简化了代码。
在服务器端(192.168.2.2 机器)我运行宁以下代码:
#! /usr/bin/python3
import socket
BUFFER_SIZE = 2 ** 9 # 1024. Keep buffer size as power of 2.
proxy_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
proxy_socket.bind(("192.168.2.2", 7900))
while True:
data, address = proxy_socket.recvfrom(BUFFER_SIZE)
print('received')
在客户端(来自 192.168.2.12 机器)我正在 运行宁此代码:
#! /usr/bin/python3
import socket
msgFromClient = "Hello UDP Server"
bytesToSend = str.encode(msgFromClient)
serverAddressPort = ("192.168.2.2", 7900)
bufferSize = 1024
# Create a UDP socket at client side
UDPClientSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
# Send to server using created UDP socket
UDPClientSocket.sendto(bytesToSend, serverAddressPort)
print('sent')
结果还是和之前一样。即使我有证据(通过 tcp 转储)数据已发送,也没有收到数据。
解决方案:
看起来有一个防火墙问题阻止了端口被监控。以下是我用来添加端口的命令:
--Adds the port to the firewall
firewall-cmd --permanent --add-port=7800/udp
--restart the firewall service for the port to take effect
systemctl restart firewalld
解决方案:
看起来有一个防火墙问题阻止了端口被监控。以下是我用来添加端口的命令:
--Adds the port to the firewall
firewall-cmd --permanent --add-port=7800/udp
--restart the firewall service for the port to take effect
systemctl restart firewalld
我想在一台机器 (192.168.2.2:7800) 上接收 UDP 以太网流量(来自另一台机器 (192.168.2.12))。
我可以通过 tcp 转储看到数据在接收机器上流动:
tcpdump -n -i enp5s0f1 udp port 7800
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on enp5s0f1, link-type EN10MB (Ethernet), capture size 262144 bytes
19:04:13.160763 IP 192.168.2.12.ovbus > 192.168.2.2.asr: UDP, length 1052
19:04:13.170854 IP 192.168.2.12.ovbus > 192.168.2.2.asr: UDP, length 1052
我已经尝试使用我从 Radoslaw Matusiak here (https://github.com/rsc-dev/pyproxy/blob/master/code/pyproxy.py) 获得的以下代码设置 IP 为 192.168.2.2 和端口为 7800 的 python UDP 服务器:
#!/usr/bin/env python
__author__ = 'Radoslaw Matusiak'
__copyright__ = 'Copyright (c) 2016 Radoslaw Matusiak'
__license__ = 'MIT'
__version__ = '0.1'
"""
TCP/UDP proxy.
"""
import argparse
import signal
import logging
import select
import socket
FORMAT = '%(asctime)-15s %(levelname)-10s %(message)s'
logging.basicConfig(format=FORMAT)
LOGGER = logging.getLogger()
LOCAL_DATA_HANDLER = lambda x:x
REMOTE_DATA_HANDLER = lambda x:x
BUFFER_SIZE = 2 ** 10 # 1024. Keep buffer size as power of 2.
def udp_proxy(src, dst):
"""Run UDP proxy.
Arguments:
src -- Source IP address and port string. I.e.: '127.0.0.1:8000'
dst -- Destination IP address and port. I.e.: '127.0.0.1:8888'
"""
LOGGER.debug('Starting UDP proxy...')
LOGGER.debug('Src: {}'.format(src))
LOGGER.debug('Dst: {}'.format(dst))
proxy_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
proxy_socket.bind(ip_to_tuple(src))
client_address = None
server_address = ip_to_tuple(dst)
LOGGER.debug('Looping proxy (press Ctrl-Break to stop)...')
while True:
data, address = proxy_socket.recvfrom(BUFFER_SIZE)
LOGGER.debug('Data Received')
if client_address == None:
client_address = address
if address == client_address:
data = LOCAL_DATA_HANDLER(data)
proxy_socket.sendto(data, server_address)
elif address == server_address:
data = REMOTE_DATA_HANDLER(data)
proxy_socket.sendto(data, client_address)
client_address = None
else:
LOGGER.warning('Unknown address: {}'.format(str(address)))
# end-of-function udp_proxy
def tcp_proxy(src, dst):
"""Run TCP proxy.
Arguments:
src -- Source IP address and port string. I.e.: '127.0.0.1:8000'
dst -- Destination IP address and port. I.e.: '127.0.0.1:8888'
"""
LOGGER.debug('Starting TCP proxy...')
LOGGER.debug('Src: {}'.format(src))
LOGGER.debug('Dst: {}'.format(dst))
sockets = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(ip_to_tuple(src))
s.listen(1)
s_src, _ = s.accept()
s_dst = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s_dst.connect(ip_to_tuple(dst))
sockets.append(s_src)
sockets.append(s_dst)
while True:
s_read, _, _ = select.select(sockets, [], [])
for s in s_read:
data = s.recv(BUFFER_SIZE)
if s == s_src:
d = LOCAL_DATA_HANDLER(data)
s_dst.sendall(d)
elif s == s_dst:
d = REMOTE_DATA_HANDLER(data)
s_src.sendall(d)
# end-of-function tcp_proxy
def ip_to_tuple(ip):
"""Parse IP string and return (ip, port) tuple.
Arguments:
ip -- IP address:port string. I.e.: '127.0.0.1:8000'.
"""
ip, port = ip.split(':')
return (ip, int(port))
# end-of-function ip_to_tuple
def main():
"""Main method."""
parser = argparse.ArgumentParser(description='TCP/UPD proxy.')
# TCP UPD groups
proto_group = parser.add_mutually_exclusive_group(required=True)
proto_group.add_argument('--tcp', action='store_true', help='TCP proxy')
proto_group.add_argument('--udp', action='store_true', help='UDP proxy')
parser.add_argument('-s', '--src', required=True, help='Source IP and port, i.e.: 127.0.0.1:8000')
parser.add_argument('-d', '--dst', required=True, help='Destination IP and port, i.e.: 127.0.0.1:8888')
output_group = parser.add_mutually_exclusive_group()
output_group.add_argument('-q', '--quiet', action='store_true', help='Be quiet')
output_group.add_argument('-v', '--verbose', action='store_true', help='Be loud')
args = parser.parse_args()
if args.quiet:
LOGGER.setLevel(logging.CRITICAL)
if args.verbose:
LOGGER.setLevel(logging.NOTSET)
if args.udp:
udp_proxy(args.src, args.dst)
elif args.tcp:
tcp_proxy(args.src, args.dst)
# end-of-function main
if __name__ == '__main__':
main()
然而,当我 运行 命令 testpyProxy.py --udp -d 192.168.2.13:7800 -s 192.168.2.2:7800 我从来没有收到:
2009-01-23 19:11:38,786 DEBUG BUFFER SIZE: 32768
2009-01-23 19:11:38,786 DEBUG Starting UDP proxy...
2009-01-23 19:11:38,786 DEBUG Src: 192.168.2.2:7800
2009-01-23 19:11:38,786 DEBUG Dst: 192.168.2.12:7800
2009-01-23 19:11:38,787 DEBUG Looping proxy (press Ctrl-Break to stop)...
此 python 代理 运行 在 Centos 7 (192.168.2.2) 机器上使用来自 ifconfig 的以太网端口连接统计信息:
enp5s0f1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 9000
inet 192.168.2.2 netmask 255.255.255.0 broadcast 192.168.2.255
inet6 fe80::21b:acff:fe02:af29 prefixlen 64 scopeid 0x20<link>
ether 00:1b:ac:02:af:29 txqueuelen 1000 (Ethernet)
RX packets 206136919 bytes 494683048962 (460.7 GiB)
RX errors 0 dropped 50795 overruns 0 frame 0
TX packets 1018446 bytes 564508158 (538.3 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
非常感谢任何帮助。
更新:
感谢 tdelaney 的建议,我已经 运行ning 简化了代码。 在服务器端(192.168.2.2 机器)我运行宁以下代码:
#! /usr/bin/python3
import socket
BUFFER_SIZE = 2 ** 9 # 1024. Keep buffer size as power of 2.
proxy_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
proxy_socket.bind(("192.168.2.2", 7900))
while True:
data, address = proxy_socket.recvfrom(BUFFER_SIZE)
print('received')
在客户端(来自 192.168.2.12 机器)我正在 运行宁此代码:
#! /usr/bin/python3
import socket
msgFromClient = "Hello UDP Server"
bytesToSend = str.encode(msgFromClient)
serverAddressPort = ("192.168.2.2", 7900)
bufferSize = 1024
# Create a UDP socket at client side
UDPClientSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
# Send to server using created UDP socket
UDPClientSocket.sendto(bytesToSend, serverAddressPort)
print('sent')
结果还是和之前一样。即使我有证据(通过 tcp 转储)数据已发送,也没有收到数据。
解决方案: 看起来有一个防火墙问题阻止了端口被监控。以下是我用来添加端口的命令:
--Adds the port to the firewall
firewall-cmd --permanent --add-port=7800/udp
--restart the firewall service for the port to take effect
systemctl restart firewalld
解决方案: 看起来有一个防火墙问题阻止了端口被监控。以下是我用来添加端口的命令:
--Adds the port to the firewall
firewall-cmd --permanent --add-port=7800/udp
--restart the firewall service for the port to take effect
systemctl restart firewalld