A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
udp-trace-client.cc
Go to the documentation of this file.
1/*
2 * Copyright (c) 2007,2008, 2009 INRIA, UDcast
3 *
4 * SPDX-License-Identifier: GPL-2.0-only
5 *
6 * Author: Mohamed Amine Ismail <amine.ismail@sophia.inria.fr>
7 * <amine.ismail@udcast.com>
8 */
9#include "udp-trace-client.h"
10
11#include "seq-ts-header.h"
12
13#include "ns3/address-utils.h"
14#include "ns3/boolean.h"
15#include "ns3/log.h"
16#include "ns3/nstime.h"
17#include "ns3/packet.h"
18#include "ns3/simulator.h"
19#include "ns3/socket-factory.h"
20#include "ns3/socket.h"
21#include "ns3/string.h"
22#include "ns3/uinteger.h"
23
24#include <cstdio>
25#include <cstdlib>
26#include <fstream>
27
28namespace ns3
29{
30
31NS_LOG_COMPONENT_DEFINE("UdpTraceClient");
32
33NS_OBJECT_ENSURE_REGISTERED(UdpTraceClient);
34
35/**
36 * @brief Default trace to send
37 */
38UdpTraceClient::TraceEntry UdpTraceClient::g_defaultEntries[] = {
39 {0, 534, 'I'},
40 {40, 1542, 'P'},
41 {120, 134, 'B'},
42 {80, 390, 'B'},
43 {240, 765, 'P'},
44 {160, 407, 'B'},
45 {200, 504, 'B'},
46 {360, 903, 'P'},
47 {280, 421, 'B'},
48 {320, 587, 'B'},
49};
50
51TypeId
53{
54 static TypeId tid =
55 TypeId("ns3::UdpTraceClient")
57 .SetGroupName("Applications")
58 .AddConstructor<UdpTraceClient>()
59 .AddAttribute("RemoteAddress",
60 "The destination Address of the outbound packets",
63 (void(UdpTraceClient::*)(const Address&)) &
64 UdpTraceClient::SetRemote), // this is needed to indicate which
65 // version of the function overload to use
68 "Replaced by Remote in ns-3.44.")
69 .AddAttribute(
70 "RemotePort",
71 "The destination port of the outbound packets",
74 (void(UdpTraceClient::*)(const Address&)) &
75 UdpTraceClient::SetRemote, // this is needed to indicate which version of
76 // the function overload to use
80 "Replaced by Remote in ns-3.44.")
81 .AddAttribute("MaxPacketSize",
82 "The maximum size of a packet (including the SeqTsHeader, 12 bytes).",
83 UintegerValue(1024),
86 .AddAttribute("TraceFilename",
87 "Name of file to load a trace from. By default, uses a hardcoded trace.",
88 StringValue(""),
91 .AddAttribute("TraceLoop",
92 "Loops through the trace file, starting again once it is over.",
93 BooleanValue(true),
96
97 ;
98 return tid;
99}
100
102 : m_sent{0},
103 m_socket{nullptr},
104 m_peerPort{},
105 m_sendEvent{},
106 m_currentEntry{0}
107{
108 NS_LOG_FUNCTION(this);
109}
110
115
116void
118{
119 NS_LOG_FUNCTION(this << ip << port);
120 SetRemote(ip);
121 SetPort(port);
122}
123
124void
126{
127 NS_LOG_FUNCTION(this << addr);
128 if (!addr.IsInvalid())
129 {
130 m_peer = addr;
131 if (m_peerPort)
132 {
134 }
135 LoadTrace();
136 }
137}
138
141{
142 return m_peer;
143}
144
145void
147{
148 NS_LOG_FUNCTION(this << port);
149 if (m_peer.IsInvalid())
150 {
151 // save for later
153 return;
154 }
156 {
158 }
159}
160
161uint16_t
178
179void
180UdpTraceClient::SetTraceFile(const std::string& traceFile)
181{
182 NS_LOG_FUNCTION(this << traceFile);
183 m_traceFile = traceFile;
184 LoadTrace();
185}
186
187void
188UdpTraceClient::SetMaxPacketSize(uint16_t maxPacketSize)
189{
190 NS_LOG_FUNCTION(this << maxPacketSize);
191 m_maxPacketSize = maxPacketSize;
192}
193
194uint16_t
200
201void
203{
204 NS_LOG_FUNCTION(this);
205 m_entries.clear();
206 m_currentEntry = 0;
207
208 if (m_traceFile.empty())
209 {
211 return;
212 }
213
214 std::ifstream ifTraceFile;
215 ifTraceFile.open(m_traceFile, std::ifstream::in);
216 if (!ifTraceFile.good())
217 {
219 return;
220 }
221
222 uint32_t oldIndex = 0;
223 uint32_t prevTime = 0;
224 while (ifTraceFile.good())
225 {
226 uint32_t index = 0;
227 char frameType;
228 uint32_t time = 0;
229 uint32_t size = 0;
230 ifTraceFile >> index >> frameType >> time >> size;
231
232 if (index == oldIndex)
233 {
234 continue;
235 }
236
237 TraceEntry entry{};
238 if (frameType == 'B')
239 {
240 entry.timeToSend = 0;
241 }
242 else
243 {
244 entry.timeToSend = time - prevTime;
245 prevTime = time;
246 }
247 entry.packetSize = size;
248 entry.frameType = frameType;
249 m_entries.push_back(entry);
250 oldIndex = index;
251 }
252
253 ifTraceFile.close();
254 NS_ASSERT_MSG(prevTime != 0, "A trace file can not contain B frames only.");
255}
256
257void
259{
260 NS_LOG_FUNCTION(this);
261 uint32_t prevTime = 0;
262 for (uint32_t i = 0; i < (sizeof(g_defaultEntries) / sizeof(TraceEntry)); i++)
263 {
264 TraceEntry entry = g_defaultEntries[i];
265 if (entry.frameType == 'B')
266 {
267 entry.timeToSend = 0;
268 }
269 else
270 {
271 uint32_t tmp = entry.timeToSend;
272 entry.timeToSend -= prevTime;
273 prevTime = tmp;
274 }
275 m_entries.push_back(entry);
276 }
277}
278
279void
281{
282 NS_LOG_FUNCTION(this);
283
284 if (!m_socket)
285 {
286 auto tid = TypeId::LookupByName("ns3::UdpSocketFactory");
288 NS_ABORT_MSG_IF(m_peer.IsInvalid(), "Remote address not properly set");
289 if (!m_local.IsInvalid())
290 {
295 "Incompatible peer and local address IP version");
296 if (m_socket->Bind(m_local) == -1)
297 {
298 NS_FATAL_ERROR("Failed to bind socket");
299 }
300 }
301 else
302 {
304 {
305 if (m_socket->Bind() == -1)
306 {
307 NS_FATAL_ERROR("Failed to bind socket");
308 }
309 }
311 {
312 if (m_socket->Bind6() == -1)
313 {
314 NS_FATAL_ERROR("Failed to bind socket");
315 }
316 }
317 else
318 {
319 NS_ASSERT_MSG(false, "Incompatible address type: " << m_peer);
320 }
321 }
322 m_socket->SetIpTos(m_tos); // Affects only IPv4 sockets.
326 }
328}
329
330void
336
337void
339{
340 NS_LOG_FUNCTION(this << size);
342 if (size > 12)
343 {
344 packetSize = size - 12; // 12 is the size of the SeqTsHeader
345 }
346 else
347 {
348 packetSize = 0;
349 }
350 auto p = Create<Packet>(packetSize);
351 SeqTsHeader seqTs;
352 seqTs.SetSeq(m_sent);
353 p->AddHeader(seqTs);
354
355 std::stringstream addressString{};
356#ifdef NS3_LOG_ENABLE
358 {
359 addressString << InetSocketAddress::ConvertFrom(m_peer).GetIpv4() << ":"
361 }
363 {
364 addressString << Inet6SocketAddress::ConvertFrom(m_peer).GetIpv6() << ":"
366 }
367#endif
368
369 if ((m_socket->Send(p)) >= 0)
370 {
371 ++m_sent;
372 NS_LOG_INFO("Sent " << size << " bytes to " << addressString.str());
373 }
374 else
375 {
376 NS_LOG_INFO("Error while sending " << size << " bytes to " << addressString.str());
377 }
378}
379
380void
382{
383 NS_LOG_FUNCTION(this);
384
386
387 bool cycled = false;
388 Ptr<Packet> p;
390 do
391 {
392 for (uint32_t i = 0; i < entry->packetSize / m_maxPacketSize; i++)
393 {
395 }
396
397 auto sizetosend = entry->packetSize % m_maxPacketSize;
398 SendPacket(sizetosend);
399
401 if (m_currentEntry >= m_entries.size())
402 {
403 m_currentEntry = 0;
404 cycled = true;
405 }
406 entry = &m_entries[m_currentEntry];
407 } while (entry->timeToSend == 0);
408
409 if (!cycled || m_traceLoop)
410 {
413 }
414}
415
416void
418{
419 m_traceLoop = traceLoop;
420}
421
422} // 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
AttributeValue implementation for Boolean.
Definition boolean.h:26
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.
Packet header to carry sequence number and timestamp.
void SetSeq(uint32_t seq)
static EventId Schedule(const Time &delay, FUNC f, Ts &&... args)
Schedule an event to expire after delay.
Definition simulator.h:560
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 EventId ScheduleNow(FUNC f, Ts &&... args)
Schedule an event to expire Now.
Definition simulator.h:594
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.
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 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.
Hold variables of type string.
Definition string.h:45
a unique identifier for an interface.
Definition type-id.h:48
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.
Definition type-id.h:64
A trace based streamer.
EventId m_sendEvent
Event to send the next packet.
void SetTraceFile(const std::string &filename)
Set the trace file to be used by the application.
void StopApplication() override
Application specific shutdown code.
Address GetRemote() const
Get the remote address (temporary function until deprecated attributes are removed)
static TypeId GetTypeId()
Get the type ID.
void Send()
Send a packet.
std::optional< uint16_t > m_peerPort
Remote peer port (deprecated) // NS_DEPRECATED_3_44.
void SetTraceLoop(bool traceLoop)
Set the trace loop flag.
uint32_t m_sent
Counter for sent packets.
std::vector< TraceEntry > m_entries
Entries in the trace to send.
uint32_t m_currentEntry
Current entry index.
void SetMaxPacketSize(uint16_t maxPacketSize)
Set the maximum packet size.
void LoadTrace()
Load current trace file.
void SetPort(uint16_t port)
Set the remote port (temporary function until deprecated attributes are removed)
void StartApplication() override
Application specific startup code.
static constexpr uint16_t DEFAULT_PORT
default port
void SetRemote(const Address &ip, uint16_t port)
set the remote address and port
void SendPacket(uint32_t size)
Send a packet of a given size.
bool m_traceLoop
Loop through the trace file.
uint16_t m_maxPacketSize
Maximum packet size to send (including the SeqTsHeader)
std::string m_traceFile
The location of the trace file.
static TraceEntry g_defaultEntries[]
Default trace to send.
uint16_t GetPort() const
Get the remote port (temporary function until deprecated attributes are removed)
uint16_t GetMaxPacketSize()
Return the maximum packet size.
void LoadDefaultTrace()
Load the default trace.
Ptr< Socket > m_socket
Socket.
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 AttributeChecker > MakeBooleanChecker()
Definition boolean.cc:113
Ptr< const AttributeAccessor > MakeBooleanAccessor(T1 a1)
Create an AttributeAccessor for a class data member, or a lone class get functor or set method.
Definition boolean.h:70
Ptr< const AttributeChecker > MakeStringChecker()
Definition string.cc:19
Ptr< const AttributeAccessor > MakeStringAccessor(T1 a1)
Create an AttributeAccessor for a class data member, or a lone class get functor or set method.
Definition string.h:46
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 MilliSeconds(uint64_t value)
Construct a Time in the indicated unit.
Definition nstime.h:1356
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.
Entry to send.
uint32_t timeToSend
Time to send the frame.
uint32_t packetSize
Size of the frame.
char frameType
Frame type (I, P or B)
Time prevTime
static const uint32_t packetSize
Packet size generated at the AP.