A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
udp-echo-client.cc
Go to the documentation of this file.
1/*
2 * Copyright 2007 University of Washington
3 *
4 * SPDX-License-Identifier: GPL-2.0-only
5 */
6#include "udp-echo-client.h"
7
8#include "ns3/address-utils.h"
9#include "ns3/log.h"
10#include "ns3/nstime.h"
11#include "ns3/packet.h"
12#include "ns3/simulator.h"
13#include "ns3/socket-factory.h"
14#include "ns3/socket.h"
15#include "ns3/trace-source-accessor.h"
16#include "ns3/uinteger.h"
17
18namespace ns3
19{
20
21NS_LOG_COMPONENT_DEFINE("UdpEchoClientApplication");
22
23NS_OBJECT_ENSURE_REGISTERED(UdpEchoClient);
24
25TypeId
27{
28 static TypeId tid =
29 TypeId("ns3::UdpEchoClient")
31 .SetGroupName("Applications")
32 .AddConstructor<UdpEchoClient>()
33 .AddAttribute(
34 "MaxPackets",
35 "The maximum number of packets the application will send (zero means infinite)",
36 UintegerValue(100),
39 .AddAttribute("Interval",
40 "The time to wait between packets",
44 // NS_DEPRECATED_3_44
45 .AddAttribute(
46 "RemoteAddress",
47 "The destination Address of the outbound packets",
50 // this is needed to indicate which version of the function overload to use
51 static_cast<void (UdpEchoClient::*)(const Address&)>(&UdpEchoClient::SetRemote),
55 "Replaced by Remote in ns-3.44.")
56 // NS_DEPRECATED_3_44
57 .AddAttribute("RemotePort",
58 "The destination port of the outbound packets",
63 "Replaced by Remote in ns-3.44.")
64 .AddAttribute(
65 "PacketSize",
66 "Size of echo data in outbound packets",
67 UintegerValue(100),
70 .AddTraceSource("Tx",
71 "A new packet is created and is sent",
73 "ns3::Packet::TracedCallback")
74 .AddTraceSource("Rx",
75 "A packet has been received",
77 "ns3::Packet::TracedCallback")
78 .AddTraceSource("TxWithAddresses",
79 "A new packet is created and is sent",
81 "ns3::Packet::TwoAddressTracedCallback")
82 .AddTraceSource("RxWithAddresses",
83 "A packet has been received",
85 "ns3::Packet::TwoAddressTracedCallback");
86 return tid;
87}
88
90 : m_dataSize{0},
91 m_data{nullptr},
92 m_sent{0},
93 m_socket{nullptr},
94 m_peerPort{},
95 m_sendEvent{}
96{
97 NS_LOG_FUNCTION(this);
98}
99
101{
102 NS_LOG_FUNCTION(this);
103 m_socket = nullptr;
104
105 delete[] m_data;
106 m_data = nullptr;
107 m_dataSize = 0;
108}
109
110void
112{
113 NS_LOG_FUNCTION(this << ip << port);
114 SetRemote(ip);
115 SetPort(port);
116}
117
118void
120{
121 NS_LOG_FUNCTION(this << addr);
122 if (!addr.IsInvalid())
123 {
124 m_peer = addr;
125 if (m_peerPort)
126 {
128 }
129 }
130}
131
134{
135 return m_peer;
136}
137
138void
140{
141 NS_LOG_FUNCTION(this << port);
142 if (m_peer.IsInvalid())
143 {
144 // save for later
146 return;
147 }
149 {
151 }
152}
153
154uint16_t
171
172void
174{
175 NS_LOG_FUNCTION(this);
176
177 if (!m_socket)
178 {
179 auto tid = TypeId::LookupByName("ns3::UdpSocketFactory");
181 NS_ABORT_MSG_IF(m_peer.IsInvalid(), "Remote address not properly set");
182 if (!m_local.IsInvalid())
183 {
188 "Incompatible peer and local address IP version");
189 if (m_socket->Bind(m_local) == -1)
190 {
191 NS_FATAL_ERROR("Failed to bind socket");
192 }
193 }
194 else
195 {
197 {
198 if (m_socket->Bind() == -1)
199 {
200 NS_FATAL_ERROR("Failed to bind socket");
201 }
202 }
204 {
205 if (m_socket->Bind6() == -1)
206 {
207 NS_FATAL_ERROR("Failed to bind socket");
208 }
209 }
210 else
211 {
212 NS_ASSERT_MSG(false, "Incompatible address type: " << m_peer);
213 }
214 }
215 m_socket->SetIpTos(m_tos); // Affects only IPv4 sockets.
219 }
220
222}
223
224void
226{
227 NS_LOG_FUNCTION(this);
228
229 if (m_socket)
230 {
231 m_socket->Close();
233 m_socket = nullptr;
234 }
235
237}
238
239void
241{
242 NS_LOG_FUNCTION(this << dataSize);
243
244 //
245 // If the client is setting the echo packet data size this way, we infer
246 // that she doesn't care about the contents of the packet at all, so
247 // neither will we.
248 //
249 delete[] m_data;
250 m_data = nullptr;
251 m_dataSize = 0;
252 m_size = dataSize;
253}
254
257{
258 NS_LOG_FUNCTION(this);
259 return m_size;
260}
261
262void
263UdpEchoClient::SetFill(std::string fill)
264{
265 NS_LOG_FUNCTION(this << fill);
266
267 uint32_t dataSize = fill.size() + 1;
268
269 if (dataSize != m_dataSize)
270 {
271 delete[] m_data;
272 m_data = new uint8_t[dataSize];
273 m_dataSize = dataSize;
274 }
275
276 memcpy(m_data, fill.c_str(), dataSize);
277
278 //
279 // Overwrite packet size attribute.
280 //
281 m_size = dataSize;
282}
283
284void
285UdpEchoClient::SetFill(uint8_t fill, uint32_t dataSize)
286{
287 NS_LOG_FUNCTION(this << fill << dataSize);
288 if (dataSize != m_dataSize)
289 {
290 delete[] m_data;
291 m_data = new uint8_t[dataSize];
292 m_dataSize = dataSize;
293 }
294
295 memset(m_data, fill, dataSize);
296
297 //
298 // Overwrite packet size attribute.
299 //
300 m_size = dataSize;
301}
302
303void
304UdpEchoClient::SetFill(uint8_t* fill, uint32_t fillSize, uint32_t dataSize)
305{
306 NS_LOG_FUNCTION(this << fill << fillSize << dataSize);
307 if (dataSize != m_dataSize)
308 {
309 delete[] m_data;
310 m_data = new uint8_t[dataSize];
311 m_dataSize = dataSize;
312 }
313
314 if (fillSize >= dataSize)
315 {
316 memcpy(m_data, fill, dataSize);
317 m_size = dataSize;
318 return;
319 }
320
321 //
322 // Do all but the final fill.
323 //
324 uint32_t filled = 0;
325 while (filled + fillSize < dataSize)
326 {
327 memcpy(&m_data[filled], fill, fillSize);
328 filled += fillSize;
329 }
330
331 //
332 // Last fill may be partial
333 //
334 memcpy(&m_data[filled], fill, dataSize - filled);
335
336 //
337 // Overwrite packet size attribute.
338 //
339 m_size = dataSize;
340}
341
342void
348
349void
351{
352 NS_LOG_FUNCTION(this);
353
355
356 Ptr<Packet> p;
357 if (m_dataSize)
358 {
359 //
360 // If m_dataSize is non-zero, we have a data buffer of the same size that we
361 // are expected to copy and send. This state of affairs is created if one of
362 // the Fill functions is called. In this case, m_size must have been set
363 // to agree with m_dataSize
364 //
366 "UdpEchoClient::Send(): m_size and m_dataSize inconsistent");
367 NS_ASSERT_MSG(m_data, "UdpEchoClient::Send(): m_dataSize but no m_data");
369 }
370 else
371 {
372 //
373 // If m_dataSize is zero, the client has indicated that it doesn't care
374 // about the data itself either by specifying the data size by setting
375 // the corresponding attribute or by not calling a SetFill function. In
376 // this case, we don't worry about it either. But we do allow m_size
377 // to have a value different from the (zero) m_dataSize.
378 //
380 }
381 Address localAddress;
382 m_socket->GetSockName(localAddress);
383 // call to the trace sinks before the packet is actually sent,
384 // so that tags added to the packet can be sent as well
385 m_txTrace(p);
386 m_txTraceWithAddresses(p, localAddress, m_peer);
387 m_socket->Send(p);
388 ++m_sent;
389
391 {
392 NS_LOG_INFO("At time " << Simulator::Now().As(Time::S) << " client sent " << m_size
393 << " bytes to " << InetSocketAddress::ConvertFrom(m_peer).GetIpv4()
395 }
397 {
398 NS_LOG_INFO("At time " << Simulator::Now().As(Time::S) << " client sent " << m_size
399 << " bytes to " << Inet6SocketAddress::ConvertFrom(m_peer).GetIpv6()
401 }
402
403 if (m_sent < m_count || m_count == 0)
404 {
406 }
407}
408
409void
411{
412 NS_LOG_FUNCTION(this << socket);
413 Address from;
414 while (auto packet = socket->RecvFrom(from))
415 {
417 {
418 NS_LOG_INFO("At time " << Simulator::Now().As(Time::S) << " client received "
419 << packet->GetSize() << " bytes from "
420 << InetSocketAddress::ConvertFrom(from).GetIpv4() << " port "
422 }
424 {
425 NS_LOG_INFO("At time " << Simulator::Now().As(Time::S) << " client received "
426 << packet->GetSize() << " bytes from "
427 << Inet6SocketAddress::ConvertFrom(from).GetIpv6() << " port "
429 }
430 Address localAddress;
431 socket->GetSockName(localAddress);
432 m_rxTrace(packet);
433 m_rxTraceWithAddresses(packet, from, localAddress);
434 }
435}
436
437} // Namespace ns3
a polymophic address class
Definition address.h:90
bool IsInvalid() const
Definition address.cc:60
AttributeValue implementation for Address.
Definition address.h:275
Ptr< Node > GetNode() const
bool IsExpired() const
This method is syntactic sugar for the ns3::Simulator::IsExpired method.
Definition event-id.cc:58
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.
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 bool IsMatchingType(const Address &address)
static bool IsMatchingType(const Address &address)
If the Address matches the type.
Smart pointer class similar to boost::intrusive_ptr.
static EventId Schedule(const Time &delay, FUNC f, Ts &&... args)
Schedule an event to expire after delay.
Definition simulator.h:561
static void Cancel(const EventId &id)
Set the cancel bit on this event: the event's associated function will not be invoked when it expires...
Definition simulator.cc:274
static Time Now()
Return the current simulation virtual time.
Definition simulator.cc:197
virtual int Send(Ptr< Packet > p, uint32_t flags)=0
Send data (or dummy data) to the remote host.
void SetIpTos(uint8_t ipTos)
Manually set IP Type of Service field.
Definition socket.cc:423
virtual bool SetAllowBroadcast(bool allowBroadcast)=0
Configure whether broadcast datagram transmissions are allowed.
virtual int Bind6()=0
Allocate a local IPv6 endpoint for this socket.
virtual int Connect(const Address &address)=0
Initiate a connection to a remote host.
virtual int GetSockName(Address &address) const =0
Get socket address.
void SetRecvCallback(Callback< void, Ptr< Socket > > receivedData)
Notify application when new data is available to be read.
Definition socket.cc:117
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:61
virtual int Close()=0
Close a socket.
virtual int Bind(const Address &address)=0
Allocate a local endpoint for this socket.
Base class for source applications.
Address m_local
Local address to bind to.
uint8_t m_tos
The packets Type of Service.
Address m_peer
Peer address.
Simulation virtual time values and global simulation resolution.
Definition nstime.h:94
@ S
second
Definition nstime.h:105
AttributeValue implementation for Time.
Definition nstime.h:1432
a unique identifier for an interface.
Definition type-id.h:49
static TypeId LookupByName(std::string name)
Get a TypeId by name.
Definition type-id.cc:872
TypeId SetParent(TypeId tid)
Set the parent TypeId.
Definition type-id.cc:1001
@ DEPRECATED
Attribute or trace source is deprecated; user is warned.
A Udp Echo client.
void SetFill(std::string fill)
Set the data fill of the packet (what is sent as data to the server) to the zero-terminated contents ...
Time m_interval
Packet inter-send time.
void Send()
Send a packet.
void StopApplication() override
Application specific shutdown code.
Ptr< Socket > m_socket
Socket.
void HandleRead(Ptr< Socket > socket)
Handle a packet reception.
static constexpr uint16_t DEFAULT_PORT
default port
EventId m_sendEvent
Event to send the next packet.
uint32_t m_size
Size of the sent packet.
void SetRemote(const Address &ip, uint16_t port)
set the remote address and port
uint32_t GetDataSize() const
Get the number of data bytes that will be sent to the server.
uint16_t GetPort() const
Get the remote port (temporary function until deprecated attributes are removed)
uint32_t m_count
Maximum number of packets the application will send.
std::optional< uint16_t > m_peerPort
Remote peer port (deprecated) // NS_DEPRECATED_3_44.
static TypeId GetTypeId()
Get the type ID.
uint8_t * m_data
packet payload data
void SetPort(uint16_t port)
Set the remote port (temporary function until deprecated attributes are removed)
uint32_t m_sent
Counter for sent packets.
void StartApplication() override
Application specific startup code.
void ScheduleTransmit(Time dt)
Schedule the next packet transmission.
TracedCallback< Ptr< const Packet >, const Address &, const Address & > m_txTraceWithAddresses
Callbacks for tracing the packet Tx events, includes source and destination addresses.
TracedCallback< Ptr< const Packet > > m_txTrace
Callbacks for tracing the packet Tx events.
TracedCallback< Ptr< const Packet >, const Address &, const Address & > m_rxTraceWithAddresses
Callbacks for tracing the packet Rx events, includes source and destination addresses.
void SetDataSize(uint32_t dataSize)
Set the data size of the packet (the number of bytes that are sent as data to the server).
TracedCallback< Ptr< const Packet > > m_rxTrace
Callbacks for tracing the packet Rx events.
Address GetRemote() const
Get the remote address (temporary function until deprecated attributes are removed)
uint32_t m_dataSize
packet payload size (must be equal to m_size)
Hold an unsigned integer type.
Definition uinteger.h:34
uint16_t port
Definition dsdv-manet.cc:33
#define NS_ASSERT(condition)
At runtime, in debugging builds, if this condition is not true, the program prints the source file,...
Definition assert.h:55
#define NS_ASSERT_MSG(condition, message)
At runtime, in debugging builds, if this condition is not true, the program prints the message to out...
Definition assert.h:75
Ptr< const AttributeChecker > MakeAddressChecker()
Definition address.cc:169
Ptr< const AttributeAccessor > MakeAddressAccessor(T1 a1)
Create an AttributeAccessor for a class data member, or a lone class get functor or set method.
Definition address.h:275
Ptr< const AttributeAccessor > MakeTimeAccessor(T1 a1)
Create an AttributeAccessor for a class data member, or a lone class get functor or set method.
Definition nstime.h:1433
Ptr< const AttributeChecker > MakeTimeChecker()
Helper to make an unbounded Time checker.
Definition nstime.h:1453
Ptr< const AttributeChecker > MakeUintegerChecker()
Definition uinteger.h:85
Ptr< const AttributeAccessor > MakeUintegerAccessor(T1 a1)
Create an AttributeAccessor for a class data member, or a lone class get functor or set method.
Definition uinteger.h:35
Callback< R, Args... > MakeNullCallback()
Definition callback.h:727
#define NS_FATAL_ERROR(msg)
Report a fatal error with a message and terminate.
#define NS_ABORT_MSG_IF(cond, msg)
Abnormal program termination if a condition is true, with a message.
Definition abort.h:97
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition log.h:191
#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:264
#define NS_OBJECT_ENSURE_REGISTERED(type)
Register an Object subclass with the TypeId system.
Definition object-base.h:35
Ptr< T > Create(Ts &&... args)
Create class instances by constructors with varying numbers of arguments and return them by Ptr.
Definition ptr.h:436
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition nstime.h:1345
Ptr< const TraceSourceAccessor > MakeTraceSourceAccessor(T a)
Create a TraceSourceAccessor which will control access to the underlying trace source.
Address ConvertToSocketAddress(const Address &address, uint16_t port)
Convert IPv4/IPv6 address with port to a socket 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:684