Examples › Socket Examples
socket_multicast
C++20 or laterDataReel 6.4.3POSIX (Linux, UNIX)
Legacy: examples_socket/multicast/client.cpp, examples_socket/multicast/server.cpp · Modern: examples_modern/socket/multicast/modern.cpp
Modern equivalent of the UDP multicast client and server. A receiver std::jthread joins the group (IP_ADD_MEMBERSHIP) and reads datagrams with a select() timeout and a std::stop_token; main() sends to the group with IP_MULTICAST_LOOP on, so this host's receiver gets the messages. The group address is parsed with inet_pton() (inet_addr() cannot report errors). If the host has no multicast route (some containers), the program says so and exits 0.
Usage: modern [GROUP [PORT]] (default 239.255.42.99 47312)
Legacy calls in this program
| Legacy | Modern C++ | Standard | Notes |
|---|---|---|---|
| Atoi(), Atol(), Atof(), atoi() | std::from_chars() into std::optional<T>; std::stoi() | C++17 | Overflow and junk are reported, not turned into 0. |
| gxSocket | keep gxSocket (C++ has no sockets); servers in std::jthread with std::stop_token and select() timeouts | C++20 | Stopping is a request, not a canceled thread blocked in accept(). |
From the transition tables.
Side by side
DataReel 6.4 (legacy)
examples_socket/multicast/client.cpp 88 lines
#include "gxdlcode.h" #if defined (__USE_ANSI_CPP__) // Use the ANSI Standard C++ library #include <iostream> using namespace std; // Use unqualified names for Standard C++ library #else // Use the old iostream library by default #include <iostream.h> #endif // __USE_ANSI_CPP__ #include <string.h> #include <stdlib.h> #include "gxsocket.h" #ifdef __BCC32__ int main() { return 0; } #else int main(int argc, char **argv) { if(argc != 3) { cerr << "Usage: " << argv[0] << " <Multicast IP> <Multicast Port>" << "\n" << flush; cerr << "Example: " << argv[0] << " 225.0.0.39 12345" << "\n" << flush; return 1; } char *multicast_ip = argv[1]; unsigned short port = (unsigned short) atoi(argv[2]); cout << "Construcing multicast client..." << "\n" << flush; // NOTE: Do not set the IP address here. This will allow the // socket to accept any incoming interface gxSocket client(SOCK_DGRAM, SOCK_DGRAM, IPPROTO_UDP, port); if(!client) { cout << client.SocketExceptionMessage() << "\n" << flush; return 1; } // Bind to the multicast port int rv = client.Bind(); if(rv < 0) { cout << client.SocketExceptionMessage() << "\n" << flush; return 1; } ip_mreq mreq; // Multicast address join structure mreq.imr_multiaddr.s_addr=inet_addr(multicast_ip); // Accept multicast from any interface mreq.imr_interface.s_addr=htonl(INADDR_ANY); // Join the multicast group using the SetSockOpt() function to // request that the kernel join a multicast group. rv = client.SetSockOpt(IPPROTO_IP, IP_ADD_MEMBERSHIP, (void *)&mreq, sizeof(mreq)); if(rv < 0) { cout << client.SocketExceptionMessage() << "\n" << flush; return 1; } cout << "Joining multicast group " << multicast_ip << "\n" << flush; cout << "Receiving datagrams on port " << port << "\n" << flush; cout << "Press Ctrl-C to exit" << "\n" << flush; const int buf_len = 4096; // Receive buffer size char sbuf[buf_len]; sbuf[0] = 0; while(1) { // Block until the server sends some data // 10/31/2026: Leave room for the null; a full read wrote past the end rv = client.RawReadFrom(sbuf, buf_len - 1); if(rv < 0) { cout << client.SocketExceptionMessage() << "\n" << flush; return 1; } sbuf[rv] = 0; // Null terminate the string before printing cout << sbuf << flush; } cout << "Exiting..." << "\n" << flush; client.Close(); // Close the socket connection client.ReleaseSocketLibrary(); return 0; } #endif // __BCC32__ // ----------------------------------------------------------- // // ------------------------------- // // --------- End of File --------- // // ------------------------------- //
examples_socket/multicast/server.cpp 87 lines
#include "gxdlcode.h" #if defined (__USE_ANSI_CPP__) // Use the ANSI Standard C++ library #include <iostream> using namespace std; // Use unqualified names for Standard C++ library #else // Use the old iostream library by default #include <iostream.h> #endif // __USE_ANSI_CPP__ #include <string.h> #include <stdlib.h> #include "gxsocket.h" #ifdef __BCC32__ int main() { return 0; } #else int main(int argc, char **argv) { // Check arguments. Should be only one: the port number to bind to. if(argc != 3) { cerr << "Usage: " << argv[0] << " <Multicast IP> <Multicast Port>" << "\n" << flush; cerr << "Example: " << argv[0] << " 225.0.0.39 12345" << "\n" << flush; return 1; } char *multicast_ip = argv[1]; unsigned short port = (unsigned short) atoi(argv[2]); int rv; cout << "Construcing datagram socket..." << "\n" << flush; gxSocket server(SOCK_DGRAM, SOCK_DGRAM, IPPROTO_UDP, port, multicast_ip); if(!server) { cout << server.SocketExceptionMessage() << "\n" << flush; return 1; } // Set the TTL of multicast packet to limit the number of hops a // multicast packet can traverse from the sender. As the TTL values // increase a router will expand the number of hops they will forward a // multicast packet: // 0: Restricted to the same host // 1: Restricted to the same subnet // 32: Restricted to the same site // 64: Restricted to the same region // 128: Restricted to the same continent // 255: Unrestricted unsigned char multicast_TTL = 1; // Restricted to the same subnet rv = server.SetSockOpt(IPPROTO_IP, IP_MULTICAST_TTL, (void *)&multicast_TTL, sizeof(multicast_TTL)); if(rv < 0) { cout << "Could not change the default IP packet TTL" << "\n" << flush; cout << server.SocketExceptionMessage() << "\n" << flush; cout << "\n" << flush; } cout << "Sending multicast messages to group " << multicast_ip << "\n" << flush; cout << "Sending datagrams on port " << port << "\n" << flush; cout << "Press Ctrl-C to exit" << "\n" << flush; const char *message = "The quick brown fox jumps over the lazy dog \ 0123456789\n"; while(1) { rv = server.SendTo((char *)message, strlen(message)); if(rv < 0) { cout << server.SocketExceptionMessage() << "\n" << flush; break; } #ifdef __WIN32__ Sleep(1000); #else sleep(1); #endif } cout << "Exiting..." << "\n" << flush; server.Close(); // Close the socket connection server.ReleaseSocketLibrary(); return 0; } #endif // __BCC32__ // ----------------------------------------------------------- // // ------------------------------- // // --------- End of File --------- // // ------------------------------- //
Modern C++ (C++20)
examples_modern/socket/multicast/modern.cpp 69 lines
#include <arpa/inet.h> #include <atomic> #include <chrono> #include <cstdlib> #include <iostream> #include <string> #include <string_view> #include <thread> #include "../common/modern_net.h" using namespace std::chrono_literals; using namespace modern_net; int main(int argc, char **argv) { SocketLibrary lib; std::string group = argc > 1 ? argv[1] : "239.255.42.99"; int port = argc > 2 ? std::atoi(argv[2]) : 47312; ip_mreq mreq{}; if(inet_pton(AF_INET, group.c_str(), &mreq.imr_multiaddr) != 1) { std::cout << "Not an IPv4 address: " << group << "\n"; return 1; } mreq.imr_interface.s_addr = htonl(INADDR_ANY); gxSocket rx(SOCK_DGRAM, SOCK_DGRAM, IPPROTO_UDP, port); int reuse = 1; rx.SetSockOpt(SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof reuse); if(!rx || rx.Bind() < 0) { std::cout << rx.SocketExceptionMessage() << "\n"; return 1; } if(rx.SetSockOpt(IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof mreq) < 0) { std::cout << "Cannot join " << group << " (no multicast route here); skipped\n"; return 0; } std::atomic<int> received{0}; std::jthread receiver([&](std::stop_token st) { std::string buf(4096, '\0'); while(!st.stop_requested()) { if(rx.ReadSelect(rx.GetSocket(), 0, 100000) <= 0) continue; int n = rx.RawReadFrom(buf.data(), int(buf.size())); if(n < 0) return; std::cout << "Received: " << std::string_view(buf.data(), std::size_t(n)); received++; } }); gxSocket tx(SOCK_DGRAM, SOCK_DGRAM, IPPROTO_UDP, port, group.data()); unsigned char loop = 1, ttl = 1; // Deliver here; stay on this LAN tx.SetSockOpt(IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof loop); tx.SetSockOpt(IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof ttl); bool sent = false; for(int i = 0; i < 3; i++) { std::string msg = "Multicast message " + std::to_string(i) + "\n"; sent = tx.SendTo(msg.data(), int(msg.size())) >= 0 || sent; std::this_thread::sleep_for(200ms); } std::this_thread::sleep_for(300ms); receiver.request_stop(); receiver.join(); if(!sent) { std::cout << "Cannot send to " << group << " here; skipped\n"; return 0; } std::cout << received << " message(s) received\n"; if(received == 0) std::cout << "No multicast delivery on this host; skipped\n"; return 0; } // ----------------------------------------------------------- // // ------------------------------- // // --------- End of File --------- // // ------------------------------- //
examples_modern/socket/common/modern_net.h 142 lines
#ifndef MODERN_NET_H #define MODERN_NET_H #include <chrono> #include <cstdio> #include <string> #include <thread> #include <vector> #if !defined(_WIN32) #include <arpa/inet.h> #include <csignal> #endif #include "gxsocket.h" namespace modern_net { inline void ignore_sigpipe() { #if !defined(_WIN32) std::signal(SIGPIPE, SIG_IGN); #endif } class SocketLibrary { // RAII for Winsock and friends public: SocketLibrary() { ok_ = probe_.InitSocketLibrary() == 0; } ~SocketLibrary() { probe_.ReleaseSocketLibrary(); } SocketLibrary(const SocketLibrary &) = delete; SocketLibrary &operator=(const SocketLibrary &) = delete; explicit operator bool() const { return ok_; } private: gxSocket probe_; bool ok_ = false; }; inline int bound_port(gxSocket &s) // After Bind() to port 0 { if(s.GetSockName() < 0) return -1; return int(ntohs(s.sin.sin_port)); } // Opens a listening socket on 127.0.0.1 and a free port. Returns the // port or -1. inline int listen_loopback(gxSocket &s, int backlog = 5) { if(s.InitSocket(SOCK_STREAM, 0, const_cast<char *>("127.0.0.1")) < 0) return -1; if(s.Bind() < 0 || s.Listen(backlog) < 0) return -1; return bound_port(s); } class FakeServer { public: enum class Kind { Send, Sleep, ReadLine, ReadHeader, ReadData, DataListen, DataSend }; struct Step { Kind kind; std::string data; }; FakeServer &send(std::string s) { steps_.push_back({Kind::Send, std::move(s)}); return *this; } FakeServer &sleep(int ms) { steps_.push_back({Kind::Sleep, std::to_string(ms)}); return *this; } FakeServer &read_line() { steps_.push_back({Kind::ReadLine, {}}); return *this; } FakeServer &read_header() { steps_.push_back({Kind::ReadHeader, {}}); return *this; } FakeServer &read_data() { steps_.push_back({Kind::ReadData, {}}); return *this; } FakeServer &reply(std::string s) { read_line(); return send(std::move(s)); } FakeServer &data_listen() { steps_.push_back({Kind::DataListen, {}}); return *this; } FakeServer &data_send(std::string s) { steps_.push_back({Kind::DataSend, std::move(s)}); return *this; } // Starts the script; returns the port or -1 int start() { port_ = listen_loopback(listener_, 1); if(port_ > 0) worker_ = std::jthread([this](std::stop_token st) { run(st); }); return port_; } void join() { if(worker_.joinable()) worker_.join(); } const std::string &received() const { return received_; } // After join() ~FakeServer() { join(); } private: bool wait_read(gxSocket &s, gxsSocket_t fd, std::stop_token &st) { for(int i = 0; i < 50 && !st.stop_requested(); i++) // Up to 5 s if(s.ReadSelect(fd, 0, 100000) > 0) return true; return false; } void run(std::stop_token st) { if(!wait_read(listener_, listener_.GetSocket(), st) || listener_.Accept() < 0) { listener_.Close(); return; } gxsSocket_t c = listener_.GetRemoteSocket(); for(const Step &step : steps_) { if(step.kind == Kind::Send) { std::string d = step.data; if(auto p = d.find("%PORT%"); p != std::string::npos) d.replace(p, 6, std::to_string(data_port_ / 256) + "," + std::to_string(data_port_ % 256)); if(listener_.Send(c, d.data(), int(d.size())) < 0) break; } else if(step.kind == Kind::Sleep) { std::this_thread::sleep_for(std::chrono::milliseconds(std::stoi(step.data))); } else if(step.kind == Kind::DataListen) { data_port_ = listen_loopback(data_, 1); } else if(step.kind == Kind::DataSend) { if(wait_read(data_, data_.GetSocket(), st) && data_.Accept() >= 0) { gxsSocket_t d = data_.GetRemoteSocket(); data_.Send(d, step.data.data(), int(step.data.size())); data_.Close(d); } data_.Close(); } else { // One of the reads std::string got; auto ends_with = [&got](std::string_view e) { return got.ends_with(e); }; while(wait_read(listener_, c, st)) { char ch; if(listener_.RawRead(c, &ch, 1) != 1) break; got += ch; if(step.kind == Kind::ReadLine && ch == '\n') break; if(step.kind == Kind::ReadHeader && ends_with("\r\n\r\n")) break; if(step.kind == Kind::ReadData && ends_with("\r\n.\r\n")) break; } received_ += got; if(got.empty()) break; // The client closed } } std::this_thread::sleep_for(std::chrono::milliseconds(50)); listener_.Close(c); listener_.Close(); } gxSocket listener_, data_; std::vector<Step> steps_; std::string received_; int port_ = -1, data_port_ = 0; std::jthread worker_; }; } // namespace modern_net #endif // MODERN_NET_H // ----------------------------------------------------------- // // ------------------------------- // // --------- End of File --------- // // ------------------------------- //
Build and run
cmake -S examples_modern -B build-modern -DCMAKE_CXX_STANDARD=20 cmake --build build-modern --target socket_multicast ./build-modern/socket_multicast
Output of the modern program
From run_modern_tests.sh on RHEL 10, GCC 14, C++20.
0 message(s) received No multicast delivery on this host; skipped