Search code examples
c++socketsudpmultiplexing

C++ UDP Socket port multiplexing


How can I create a client UDP socket in C++ so that it can listen on a port which is being listened to by another application? In other words, how can I apply port multiplexing in C++?


Solution

  • I want to listen on only one port

    You can do that with a sniffer. Just ignore the packets from different ports.

    I might need to stop it from sending out some particular packets, because my program will send it instead of the original application

    Okay, here I suggest you to discard sniffers, and use a MITM technique.

    You'll need to rely on a PREROUTING firewall rule to divert the packets to a "proxy" application. Assuming UDP, Linux, iptables, and the "proxy" running on the same host, here's what the "proxy" actually needs to do:

    1. Add the firewall rule to divert the packets (do it manually, if you prefer):

    iptables -t nat -A PREROUTING -i <iface> -p <proto> --dport <dport>
        -j REDIRECT --to-port <newport>
    

    2. Bind and listen on <newport>.

    3. Relay all the traffic between the 2 endpoints (client, and original destination). If you're running the "proxy" on a different host, use getsockopt with SO_ORIGINAL_DST to retrieve the original destination address.

    It might sound tricky, but... yeah, that's because it's a bit tricky :-) Consult your firewall documentation if my assumption diverges.