Question

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

Was it helpful?

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.

OTHER TIPS

This is just packet sniffing like tcpdump or snoop, open up a raw socket and pull everything from the wire and filter as you require. You will probably want to use libpcap to make things a little easier.

Without administrator or super-user privileges you will need the target application to open ports with SO_REUSEADDR and SO_REUSEPORT as appropriate for the platform. The caveat being you can only receive broadcast and multicast packets, unicast packets are delivered to the first open socket.

This is not multiplexing - that term is reserved for handling I/O on multiple channels in the same process and where things like select(2) and poll(2) are most useful.

What you are asking for is multicast. Here is the basic example.

Note that IP reserves a special range of addresses (a.k.a. groups) for multicasting. These get mapped to special ethernet addresses. The listener(s) would have to join the multicast group, while sender does not have to, it just sends as usual.

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top