A Discrete-Event Network Simulator
API
udp-echo-server.cc
Go to the documentation of this file.
1 /*
2  * Copyright 2007 University of Washington
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License version 2 as
6  * published by the Free Software Foundation;
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11  * GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this program; if not, write to the Free Software
15  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16  */
17 
18 #include "udp-echo-server.h"
19 
20 #include "ns3/address-utils.h"
21 #include "ns3/inet-socket-address.h"
22 #include "ns3/inet6-socket-address.h"
23 #include "ns3/ipv4-address.h"
24 #include "ns3/ipv6-address.h"
25 #include "ns3/log.h"
26 #include "ns3/nstime.h"
27 #include "ns3/packet.h"
28 #include "ns3/simulator.h"
29 #include "ns3/socket-factory.h"
30 #include "ns3/socket.h"
31 #include "ns3/udp-socket.h"
32 #include "ns3/uinteger.h"
33 
34 namespace ns3
35 {
36 
37 NS_LOG_COMPONENT_DEFINE("UdpEchoServerApplication");
38 
39 NS_OBJECT_ENSURE_REGISTERED(UdpEchoServer);
40 
41 TypeId
43 {
44  static TypeId tid =
45  TypeId("ns3::UdpEchoServer")
47  .SetGroupName("Applications")
48  .AddConstructor<UdpEchoServer>()
49  .AddAttribute("Port",
50  "Port on which we listen for incoming packets.",
51  UintegerValue(9),
53  MakeUintegerChecker<uint16_t>())
54  .AddTraceSource("Rx",
55  "A packet has been received",
57  "ns3::Packet::TracedCallback")
58  .AddTraceSource("RxWithAddresses",
59  "A packet has been received",
61  "ns3::Packet::TwoAddressTracedCallback");
62  return tid;
63 }
64 
66 {
67  NS_LOG_FUNCTION(this);
68 }
69 
71 {
72  NS_LOG_FUNCTION(this);
73  m_socket = nullptr;
74  m_socket6 = nullptr;
75 }
76 
77 void
79 {
80  NS_LOG_FUNCTION(this);
82 }
83 
84 void
86 {
87  NS_LOG_FUNCTION(this);
88 
89  if (!m_socket)
90  {
91  TypeId tid = TypeId::LookupByName("ns3::UdpSocketFactory");
94  if (m_socket->Bind(local) == -1)
95  {
96  NS_FATAL_ERROR("Failed to bind socket");
97  }
99  {
100  Ptr<UdpSocket> udpSocket = DynamicCast<UdpSocket>(m_socket);
101  if (udpSocket)
102  {
103  // equivalent to setsockopt (MCAST_JOIN_GROUP)
104  udpSocket->MulticastJoinGroup(0, m_local);
105  }
106  else
107  {
108  NS_FATAL_ERROR("Error: Failed to join multicast group");
109  }
110  }
111  }
112 
113  if (!m_socket6)
114  {
115  TypeId tid = TypeId::LookupByName("ns3::UdpSocketFactory");
118  if (m_socket6->Bind(local6) == -1)
119  {
120  NS_FATAL_ERROR("Failed to bind socket");
121  }
122  if (addressUtils::IsMulticast(local6))
123  {
124  Ptr<UdpSocket> udpSocket = DynamicCast<UdpSocket>(m_socket6);
125  if (udpSocket)
126  {
127  // equivalent to setsockopt (MCAST_JOIN_GROUP)
128  udpSocket->MulticastJoinGroup(0, local6);
129  }
130  else
131  {
132  NS_FATAL_ERROR("Error: Failed to join multicast group");
133  }
134  }
135  }
136 
139 }
140 
141 void
143 {
144  NS_LOG_FUNCTION(this);
145 
146  if (m_socket)
147  {
148  m_socket->Close();
150  }
151  if (m_socket6)
152  {
153  m_socket6->Close();
155  }
156 }
157 
158 void
160 {
161  NS_LOG_FUNCTION(this << socket);
162 
163  Ptr<Packet> packet;
164  Address from;
165  Address localAddress;
166  while ((packet = socket->RecvFrom(from)))
167  {
168  socket->GetSockName(localAddress);
169  m_rxTrace(packet);
170  m_rxTraceWithAddresses(packet, from, localAddress);
172  {
173  NS_LOG_INFO("At time " << Simulator::Now().As(Time::S) << " server received "
174  << packet->GetSize() << " bytes from "
175  << InetSocketAddress::ConvertFrom(from).GetIpv4() << " port "
177  }
178  else if (Inet6SocketAddress::IsMatchingType(from))
179  {
180  NS_LOG_INFO("At time " << Simulator::Now().As(Time::S) << " server received "
181  << packet->GetSize() << " bytes from "
182  << Inet6SocketAddress::ConvertFrom(from).GetIpv6() << " port "
184  }
185 
186  packet->RemoveAllPacketTags();
187  packet->RemoveAllByteTags();
188 
189  NS_LOG_LOGIC("Echoing packet");
190  socket->SendTo(packet, 0, from);
191 
193  {
194  NS_LOG_INFO("At time " << Simulator::Now().As(Time::S) << " server sent "
195  << packet->GetSize() << " bytes to "
196  << InetSocketAddress::ConvertFrom(from).GetIpv4() << " port "
198  }
199  else if (Inet6SocketAddress::IsMatchingType(from))
200  {
201  NS_LOG_INFO("At time " << Simulator::Now().As(Time::S) << " server sent "
202  << packet->GetSize() << " bytes to "
203  << Inet6SocketAddress::ConvertFrom(from).GetIpv6() << " port "
205  }
206  }
207 }
208 
209 } // Namespace ns3
a polymophic address class
Definition: address.h:101
The base class for all ns3 applications.
Definition: application.h:62
void DoDispose() override
Destructor implementation.
Definition: application.cc:86
Ptr< Node > GetNode() const
Definition: application.cc:108
An Inet6 address class.
static Inet6SocketAddress ConvertFrom(const Address &addr)
Convert the address to a InetSocketAddress.
uint16_t GetPort() const
Get the port.
static bool IsMatchingType(const Address &addr)
If the address match.
Ipv6Address GetIpv6() const
Get the IPv6 address.
an Inet address class
static bool IsMatchingType(const Address &address)
Ipv4Address GetIpv4() const
static InetSocketAddress ConvertFrom(const Address &address)
Returns an InetSocketAddress which corresponds to the input Address.
static Ipv4Address GetAny()
static Ipv6Address GetAny()
Get the "any" (::) Ipv6Address.
uint32_t GetSize() const
Returns the the size in bytes of the packet (including the zero-filled initial payload).
Definition: packet.h:861
void RemoveAllByteTags()
Remove all byte tags stored in this packet.
Definition: packet.cc:393
void RemoveAllPacketTags()
Remove all packet tags.
Definition: packet.cc:990
Smart pointer class similar to boost::intrusive_ptr.
Definition: ptr.h:77
static Time Now()
Return the current simulation virtual time.
Definition: simulator.cc:208
void SetRecvCallback(Callback< void, Ptr< Socket >> receivedData)
Notify application when new data is available to be read.
Definition: socket.cc:128
virtual int GetSockName(Address &address) const =0
Get socket address.
static Ptr< Socket > CreateSocket(Ptr< Node > node, TypeId tid)
This method wraps the creation of sockets that is performed on a given node by a SocketFactory specif...
Definition: socket.cc:72
virtual int Close()=0
Close a socket.
virtual int Bind(const Address &address)=0
Allocate a local endpoint for this socket.
virtual Ptr< Packet > RecvFrom(uint32_t maxSize, uint32_t flags, Address &fromAddress)=0
Read a single packet from the socket and retrieve the sender address.
virtual int SendTo(Ptr< Packet > p, uint32_t flags, const Address &toAddress)=0
Send data to a specified peer.
@ S
second
Definition: nstime.h:116
a unique identifier for an interface.
Definition: type-id.h:59
static TypeId LookupByName(std::string name)
Get a TypeId by name.
Definition: type-id.cc:835
TypeId SetParent(TypeId tid)
Set the parent TypeId.
Definition: type-id.cc:931
A Udp Echo server.
void StartApplication() override
Application specific startup code.
uint16_t m_port
Port on which we listen for incoming packets.
Address m_local
local multicast address
TracedCallback< Ptr< const Packet >, const Address &, const Address & > m_rxTraceWithAddresses
Callbacks for tracing the packet Rx events, includes source and destination addresses.
void DoDispose() override
Destructor implementation.
Ptr< Socket > m_socket6
IPv6 Socket.
static TypeId GetTypeId()
Get the type ID.
void StopApplication() override
Application specific shutdown code.
TracedCallback< Ptr< const Packet > > m_rxTrace
Callbacks for tracing the packet Rx events.
~UdpEchoServer() override
Ptr< Socket > m_socket
IPv4 Socket.
void HandleRead(Ptr< Socket > socket)
Handle a packet reception.
Hold an unsigned integer type.
Definition: uinteger.h:45
Callback< R, Args... > MakeNullCallback()
Definition: callback.h:747
#define NS_FATAL_ERROR(msg)
Report a fatal error with a message and terminate.
Definition: fatal-error.h:179
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition: log.h:202
#define NS_LOG_LOGIC(msg)
Use NS_LOG to output a message of level LOG_LOGIC.
Definition: log.h:282
#define NS_LOG_FUNCTION(parameters)
If log level LOG_FUNCTION is enabled, this macro will output all input parameters separated by ",...
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition: log.h:275
#define NS_OBJECT_ENSURE_REGISTERED(type)
Register an Object subclass with the TypeId system.
Definition: object-base.h:46
Ptr< const TraceSourceAccessor > MakeTraceSourceAccessor(T a)
Create a TraceSourceAccessor which will control access to the underlying trace source.
bool IsMulticast(const Address &ad)
Address family-independent test for a multicast address.
Every class exported by the ns3 library is enclosed in the ns3 namespace.
Callback< R, Args... > MakeCallback(R(T::*memPtr)(Args...), OBJ objPtr)
Build Callbacks for class method members which take varying numbers of arguments and potentially retu...
Definition: callback.h:704
Ptr< const AttributeAccessor > MakeUintegerAccessor(T1 a1)
Definition: uinteger.h:46