1//
2// MulticastEchoServer.cpp
3//
4// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
5// and Contributors.
6//
7// SPDX-License-Identifier: BSL-1.0
8//
9
10
11#include "MulticastEchoServer.h"
12
13
14#ifdef POCO_NET_HAS_INTERFACE
15
16
17#include "Poco/Timespan.h"
18#include <iostream>
19
20
21using Poco::Net::Socket;
22using Poco::Net::DatagramSocket;
23using Poco::Net::SocketAddress;
24using Poco::Net::IPAddress;
25using Poco::Net::NetworkInterface;
26
27
28MulticastEchoServer::MulticastEchoServer():
29 _group("239.255.1.2", 12345),
30 _if(findInterface()),
31 _thread("MulticastEchoServer"),
32 _stop(false)
33{
34 _socket.bind(SocketAddress(IPAddress(), _group.port()), true);
35 _socket.joinGroup(_group.host(), _if);
36 _thread.start(*this);
37 _ready.wait();
38}
39
40
41MulticastEchoServer::~MulticastEchoServer()
42{
43 _stop = true;
44 _thread.join();
45 _socket.leaveGroup(_group.host(), _if);
46}
47
48
49Poco::UInt16 MulticastEchoServer::port() const
50{
51 return _socket.address().port();
52}
53
54
55void MulticastEchoServer::run()
56{
57 _ready.set();
58 Poco::Timespan span(250000);
59 while (!_stop)
60 {
61 if (_socket.poll(span, Socket::SELECT_READ))
62 {
63 try
64 {
65 char buffer[256];
66 SocketAddress sender;
67 int n = _socket.receiveFrom(buffer, sizeof(buffer), sender);
68 _socket.sendTo(buffer, n, sender);
69 }
70 catch (Poco::Exception& exc)
71 {
72 std::cerr << "MulticastEchoServer: " << exc.displayText() << std::endl;
73 }
74 }
75 }
76}
77
78
79const SocketAddress& MulticastEchoServer::group() const
80{
81 return _group;
82}
83
84
85const NetworkInterface& MulticastEchoServer::interfc() const
86{
87 return _if;
88}
89
90
91Poco::Net::NetworkInterface MulticastEchoServer::findInterface()
92{
93 NetworkInterface::Map m = NetworkInterface::map();
94 for (NetworkInterface::Map::const_iterator it = m.begin(); it != m.end(); ++it)
95 {
96 if (it->second.supportsIPv4() &&
97 it->second.firstAddress(IPAddress::IPv4).isUnicast() &&
98 !it->second.isLoopback() &&
99 !it->second.isPointToPoint())
100 {
101 return it->second;
102 }
103 }
104 return NetworkInterface();
105}
106
107#endif // POCO_NET_HAS_INTERFACE
108