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++?
Multiplexing and Demultiplexing services are provided in almost every protocol architecture ever designed. UDP and TCP perform the demultiplexing and multiplexing jobs by including two special fields in the segment headers: the source port number field and the destination port number field.
Bind both sockets to the server address. Initialize a descriptor set for select and calculate a maximum of 2 descriptors for which we will wait. Call select and get the ready descriptor(TCP or UDP) Handle new connection if the ready descriptor is of TCP OR receive datagram if the ready descriptor is of UDP.
TCP and UDP ports are not related to each other. TCP ports are interpreted by the TCP stack, while the UDP stack interprets UDP ports. Ports are a way of multiplexing the connection so that multiple devices can connect to a node.
Datagram sockets allow processes to use UDP to communicate. A datagram socket supports bidirectional flow of messages. A process on a datagram socket can receive messages in a different order from the sending sequence and can receive duplicate messages. Record boundaries in the data are preserved.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With