Home > OS >  Python UDP Server Not Receiving Data
Python UDP Server Not Receiving Data

Time:04-13

I have UDP ethernet traffic that I want to receive on a machine (192.168.2.2:7800) (coming from a separate machine (192.168.2.12)).

I can see the data is flowing on the receive machine by doing a tcp dump:

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

I have tried setting up a python UDP server with the IP of 192.168.2.2 and a port of 7800 using the following code which I got from Radoslaw Matusiak here (https://github.com/rsc-dev/pyproxy/blob/master/code/pyproxy.py):

#!/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()

However, when I run the command testpyProxy.py --udp -d 192.168.2.13:7800 -s 192.168.2.2:7800 I never get a receive:

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)...

This python proxy is running on a Centos 7 (192.168.2.2) machine with the ethernet port connection stats from 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

Any help is greatly appreciated.

UPDATE:

I have simplified the code that I am running thanks to a suggestion from tdelaney. On the server side (192.168.2.2 machine) I am running the following code:

#! /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')

On the client side (from 192.168.2.12 machine) I am running this code:

#! /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')

I still have the same result as before. No received data even though I have evidence (through tcp dump) that the data was sent.

SOLUTION: Looks like there was a firewall issue preventing the port from being monitored. The following were the commands that I took to add the port:

--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

CodePudding user response:

SOLUTION: Looks like there was a firewall issue preventing the port from being monitored. The following were the commands that I took to add the port:

--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
  • Related