A Discrete-Event Network Simulator
API
v4traceroute.cc
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright (c) 2019 Ritsumeikan University, Shiga, Japan
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License version 2 as
7  * published by the Free Software Foundation;
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  *
18  * Author: Alberto Gallegos Ramonet
19  *
20  * Traceroute uses ICMPV4 echo messages to trace all the middle hops to a given destination.
21  * It also shows the delay time it takes for a round trip to complete for each
22  * set probe (default 3).
23  *
24  */
25 
26 
27 #include "v4traceroute.h"
28 #include "ns3/icmpv4.h"
29 #include "ns3/icmpv4-l4-protocol.h"
30 #include "ns3/assert.h"
31 #include "ns3/log.h"
32 #include "ns3/ipv4-address.h"
33 #include "ns3/socket.h"
34 #include "ns3/uinteger.h"
35 #include "ns3/boolean.h"
36 #include "ns3/inet-socket-address.h"
37 #include "ns3/packet.h"
38 #include "ns3/trace-source-accessor.h"
39 
40 
41 namespace ns3 {
42 
43 NS_LOG_COMPONENT_DEFINE ("V4TraceRoute");
44 NS_OBJECT_ENSURE_REGISTERED (V4TraceRoute);
45 
46 TypeId
48 {
49  static TypeId tid = TypeId ("ns3::V4TraceRoute")
51  .SetGroupName ("Internet-Apps")
52  .AddConstructor<V4TraceRoute> ()
53  .AddAttribute ("Remote",
54  "The address of the machine we want to trace.",
58  .AddAttribute ("Verbose",
59  "Produce usual output.",
60  BooleanValue (true),
63  .AddAttribute ("Interval", "Wait interval between sent packets.",
64  TimeValue (Seconds (0)),
66  MakeTimeChecker ())
67  .AddAttribute ("Size", "The number of data bytes to be sent, real packet will be 8 (ICMP) + 20 (IP) bytes longer.",
68  UintegerValue (56),
70  MakeUintegerChecker<uint32_t> ())
71  .AddAttribute ("MaxHop", "The maximum number of hops to trace.",
72  UintegerValue (30),
74  MakeUintegerChecker<uint32_t> ())
75  .AddAttribute ("ProbeNum", "The number of packets send to each hop.",
76  UintegerValue (3),
78  MakeUintegerChecker<uint16_t> ())
79  .AddAttribute ("Timeout", "The waiting time for a route response before a timeout.",
80  TimeValue (Seconds (5)),
82  MakeTimeChecker ())
83  ;
84  return tid;
85 }
86 
87 
89  : m_interval (Seconds (0)),
90  m_size (56),
91  m_socket (0),
92  m_seq (0),
93  m_verbose (true),
94  m_probeCount (0),
95  m_maxProbes (3),
96  m_ttl (1),
97  m_maxTtl (30),
98  m_waitIcmpReplyTimeout (Seconds (5))
99 {
100  osRoute.clear ();
101  routeIpv4.clear ();
102 
103 }
104 
106 {
107 
108 }
109 
110 
111 void
113 {
114  printStream = stream;
115 }
116 
117 void
119 {
120  NS_LOG_FUNCTION (this);
121  NS_LOG_LOGIC ("Application started");
123 
124  if (m_verbose)
125  {
126  NS_LOG_UNCOND("Traceroute to " << m_remote << ", "
127  << m_maxTtl << " hops Max, "
128  << m_size << " bytes of data.");
129  }
130 
131  if (printStream != NULL)
132  {
133  *printStream->GetStream () << "Traceroute to " << m_remote << ", "
134  << m_maxTtl << " hops Max, "
135  << m_size << " bytes of data.\n";
136  }
137 
138 
139  m_socket = Socket::CreateSocket (GetNode (), TypeId::LookupByName ("ns3::Ipv4RawSocketFactory"));
141 
142 
143  NS_ASSERT (m_socket != 0);
145 
147  int status;
148  status = m_socket->Bind (src);
149  NS_ASSERT (status != -1);
150 
152 }
153 
154 
155 
156 void
158 {
159  NS_LOG_FUNCTION (this);
160 
161  if (m_next.IsRunning ())
162  {
163  m_next.Cancel ();
164  }
165 
167  {
169  }
170 
171  if (m_socket)
172  {
173  m_socket->Close ();
174  }
175 
176  if (m_verbose)
177  {
178  NS_LOG_UNCOND("\nTrace Complete");
179  }
180 
181  if (printStream != NULL)
182  {
183  *printStream->GetStream () << "Trace Complete\n" << std::endl;
184  }
185 }
186 
187 void
189 {
190  NS_LOG_FUNCTION (this);
191 
193  {
194  StopApplication ();
195  }
196 
197  m_socket = 0;
199 }
200 
201 
202 uint32_t
204 {
205  NS_LOG_FUNCTION (this);
206  Ptr<Node> node = GetNode ();
207  for (uint32_t i = 0; i < node->GetNApplications (); ++i)
208  {
209  if (node->GetApplication (i) == this)
210  {
211  return i;
212  }
213  }
214  NS_ASSERT_MSG (false, "forgot to add application to node");
215  return 0;
216 }
217 
218 void
220 {
221  NS_LOG_FUNCTION (this << socket);
222 
223  while (m_socket->GetRxAvailable () > 0)
224  {
225  Address from;
226  Ptr<Packet> p = m_socket->RecvFrom (0xffffffff, 0, from);
227  NS_LOG_DEBUG ("recv " << p->GetSize () << " bytes");
230  NS_ASSERT (realFrom.GetPort () == 1);
231  Ipv4Header ipv4;
232  p->RemoveHeader (ipv4);
233  NS_ASSERT (ipv4.GetProtocol () == Icmpv4L4Protocol::PROT_NUMBER);
234  Icmpv4Header icmp;
235  p->RemoveHeader (icmp);
236 
237 
238 
239  if (icmp.GetType () == Icmpv4Header::ICMPV4_TIME_EXCEEDED)
240  {
241 
242  Icmpv4TimeExceeded timeoutResp;
243  p->RemoveHeader (timeoutResp);
244 
245  // GetData () gets 64 bits of data, but the received packet
246  // only contains 32 bits of data.
247  uint8_t data [8];
248  timeoutResp.GetData (data);
249 
250  // Get the 7th and 8th Octect to obtain the Sequence number from
251  // the original packet.
252  uint16_t recvSeq;
253  recvSeq = (uint16_t) data[7] << 0;
254  recvSeq |= (uint16_t) data [6] << 8;
255 
256 
257  std::map<uint16_t, Time>::iterator i = m_sent.find (recvSeq);
258  if (i != m_sent.end ())
259  {
260  Time sendTime = i->second;
261  NS_ASSERT (Simulator::Now () >= sendTime);
262  Time delta = Simulator::Now () - sendTime;
263 
264  routeIpv4.str ("");
265  routeIpv4.clear ();
266  routeIpv4 << realFrom.GetIpv4 ();
267  osRoute << delta.GetMilliSeconds () << " ms ";
268  if (m_probeCount == m_maxProbes)
269  {
270  if (m_verbose)
271  {
272  NS_LOG_UNCOND(m_ttl << " " << routeIpv4.str () << " " << osRoute.str ());
273  }
274 
275  if (printStream != NULL)
276  {
277  *printStream->GetStream () << m_ttl << " "
278  << routeIpv4.str () << " "
279  << osRoute.str () << "\n";
280  }
281  osRoute.str ("");
282  osRoute.clear ();
283  routeIpv4.str ("");
284  routeIpv4.clear ();
285 
286  }
287 
289 
290  if (m_ttl < m_maxTtl + 1)
291  {
293  }
294  }
295 
296  }
297  else if (icmp.GetType () == Icmpv4Header::ICMPV4_ECHO_REPLY && m_remote == realFrom.GetIpv4 ())
298  {
299  // When UDP is used, TraceRoute should stop until ICMPV4_DEST_UNREACH
300  // (with code (3) PORT_UNREACH) is received, however, the current
301  // ns-3 implementation does not include the UDP version of traceroute.
302  // The traceroute ICMP version (the current version) stops until max_ttl is reached
303  // or until an ICMP ECHO REPLY is received m_maxProbes times.
304 
305  Icmpv4Echo echo;
306  p->RemoveHeader (echo);
307  std::map<uint16_t, Time>::iterator i = m_sent.find (echo.GetSequenceNumber ());
308 
309  if (i != m_sent.end () && echo.GetIdentifier () == 0)
310  {
311  uint32_t * buf = new uint32_t [m_size];
312  uint32_t dataSize = echo.GetDataSize ();
313 
314  if (dataSize == m_size)
315  {
316  echo.GetData ((uint8_t *)buf);
317 
318  Time sendTime = i->second;
319  NS_ASSERT (Simulator::Now () >= sendTime);
320  Time delta = Simulator::Now () - sendTime;
321 
322  m_sent.erase (i);
323 
324  if (m_verbose)
325  {
326  routeIpv4.str ("");
327  routeIpv4.clear ();
328  routeIpv4 << realFrom.GetIpv4 ();
329  osRoute << delta.GetMilliSeconds () << " ms ";
330 
331  if (m_probeCount == m_maxProbes)
332  {
333  NS_LOG_UNCOND(m_ttl << " " << routeIpv4.str () << " " << osRoute.str ());
334  if (printStream != NULL)
335  {
336  *printStream->GetStream () << m_ttl << " "
337  << routeIpv4.str () << " "
338  << osRoute.str () << "\n";
339  }
340 
341  osRoute.clear ();
342  routeIpv4.clear ();
343  }
344  }
345  }
346  delete[] buf;
347  }
348 
350  if (m_probeCount == m_maxProbes)
351  {
352  StopApplication ();
353  }
354  else if (m_ttl < m_maxTtl + 1)
355  {
357  }
358  }
359  }
360 }
361 
362 
363 
364 
365 void
367 {
368  NS_LOG_INFO ("m_seq=" << m_seq);
369  Ptr<Packet> p = Create<Packet> ();
370  Icmpv4Echo echo;
371  echo.SetSequenceNumber (m_seq);
372  m_seq++;
373  echo.SetIdentifier (0);
374 
375  //
376  // We must write quantities out in some form of network order. Since there
377  // isn't an htonl to work with we just follow the convention in pcap traces
378  // (where any difference would show up anyway) and borrow that code. Don't
379  // be too surprised when you see that this is a little endian convention.
380  //
381  uint8_t* data = new uint8_t[m_size];
382  for (uint32_t i = 0; i < m_size; ++i)
383  {
384  data[i] = 0;
385  }
386  NS_ASSERT (m_size >= 16);
387 
388  Ptr<Packet> dataPacket = Create<Packet> ((uint8_t *) data, m_size);
389  echo.SetData (dataPacket);
390  p->AddHeader (echo);
391  Icmpv4Header header;
393  header.SetCode (0);
394  if (Node::ChecksumEnabled ())
395  {
396  header.EnableChecksum ();
397  }
398 
399  p->AddHeader (header);
400 
402  {
403  m_probeCount++;
404  }
405  else
406  {
407  m_probeCount = 1;
408  m_ttl++;
409  }
410 
411  m_sent.insert (std::make_pair (m_seq - 1, Simulator::Now ()));
413 
414 
416  m_socket->SendTo (p, 0, dst);
417 
418  delete[] data;
419 
420 }
421 
422 
423 void
425 {
426  NS_LOG_FUNCTION (this);
428  {
429  NS_LOG_LOGIC ("Starting WaitIcmpReplyTimer at " << Simulator::Now () << " for " <<
431 
434  Send ();
435  }
436 }
437 
438 
439 void
441 {
442  if (m_ttl < m_maxTtl + 1)
443  {
445  }
446 
447  osRoute << "* ";
448  if (m_probeCount == m_maxProbes)
449  {
450  if (m_verbose)
451  {
452  NS_LOG_UNCOND(m_ttl << " " << routeIpv4.str () << " " << osRoute.str ());
453  }
454 
455  if (printStream != NULL)
456  {
457  *printStream->GetStream () << m_ttl
458  << " " << routeIpv4.str () << " "
459  << osRoute.str () << "\n";
460  }
461  osRoute.str ("");
462  osRoute.clear ();
463  routeIpv4.str ("");
464  routeIpv4.clear ();
465  }
466 }
467 
468 
469 } // ns3 namespace
uint32_t RemoveHeader(Header &header)
Deserialize and remove the header from the internal buffer.
Definition: packet.cc:280
void SetType(uint8_t type)
Set ICMP type.
Definition: icmpv4.cc:109
Simulation virtual time values and global simulation resolution.
Definition: nstime.h:102
an Inet address class
static Ipv4Address GetAny(void)
#define NS_LOG_FUNCTION(parameters)
If log level LOG_FUNCTION is enabled, this macro will output all input parameters separated by "...
uint32_t m_maxTtl
The maximium Ttl (Max number of hops to trace)
Definition: v4traceroute.h:121
virtual void StopApplication(void)
Application specific shutdown code.
Time m_started
Start time to report total ping time.
Definition: v4traceroute.h:111
AttributeValue implementation for Boolean.
Definition: boolean.h:36
#define NS_OBJECT_ENSURE_REGISTERED(type)
Register an Object subclass with the TypeId system.
Definition: object-base.h:45
uint32_t GetSize(void) const
Returns the the size in bytes of the packet (including the zero-filled initial payload).
Definition: packet.h:852
NS_ASSERT_MSG(false, "Ipv4AddressGenerator::MaskToIndex(): Impossible")
virtual void DoDispose(void)
Destructor implementation.
uint32_t GetData(uint8_t payload[]) const
Get the Echo data.
Definition: icmpv4.cc:191
uint32_t GetDataSize(void) const
Get the Echo data size.
Definition: icmpv4.cc:185
ICMP Time Exceeded header.
Definition: icmpv4.h:246
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:84
static bool ChecksumEnabled(void)
Definition: node.cc:276
bool m_verbose
produce traceroute style output if true
Definition: v4traceroute.h:109
#define NS_ASSERT(condition)
At runtime, in debugging builds, if this condition is not true, the program prints the source file...
Definition: assert.h:67
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition: log.h:204
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition: log.h:280
Ptr< Socket > m_socket
The socket we send packets from.
Definition: v4traceroute.h:105
void HandleWaitReplyTimeout()
Triggers an action if an ICMP TIME EXCEED have not being received in the time defined by StartWaitRep...
void Receive(Ptr< Socket > socket)
Receive an ICMP Echo.
Base class for all the ICMP packet headers.
Definition: icmpv4.h:40
Ipv4Address m_remote
Remote address.
Definition: v4traceroute.h:94
Time m_waitIcmpReplyTimeout
The wait time until the response is considered lost.
Definition: v4traceroute.h:123
virtual ~V4TraceRoute()
a polymophic address class
Definition: address.h:90
Ptr< const AttributeChecker > MakeTimeChecker(const Time min, const Time max)
Helper to make a Time checker with bounded range.
Definition: time.cc:446
void SetCode(uint8_t code)
Set ICMP code.
Definition: icmpv4.cc:115
Packet header for IPv4.
Definition: ipv4-header.h:33
u_int16_t m_maxProbes
The maximum number of probe packets per hop.
Definition: v4traceroute.h:117
static EventId Schedule(Time const &delay, MEM mem_ptr, OBJ obj)
Schedule an event to expire after delay.
Definition: simulator.h:1389
The base class for all ns3 applications.
Definition: application.h:60
AttributeValue implementation for Time.
Definition: nstime.h:1124
Ptr< const AttributeChecker > MakeIpv4AddressChecker(void)
void EnableChecksum(void)
Enables ICMP Checksum calculation.
Definition: icmpv4.cc:57
static TypeId GetTypeId(void)
Get the type ID.
Definition: v4traceroute.cc:47
Hold an unsigned integer type.
Definition: uinteger.h:44
uint8_t data[writeSize]
Ptr< Application > GetApplication(uint32_t index) const
Retrieve the index-th Application associated to this node.
Definition: node.cc:168
void StartWaitReplyTimer()
Starts a timer after sending an ICMP ECHO.
Callback< R > MakeCallback(R(T::*memPtr)(void), OBJ objPtr)
Definition: callback.h:1489
void SetRecvCallback(Callback< void, Ptr< Socket > >)
Notify application when new data is available to be read.
Definition: socket.cc:128
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:71
EventId m_waitIcmpReplyTimer
The timer used to wait for the probes ICMP replies.
Definition: v4traceroute.h:125
Ptr< Node > GetNode() const
Definition: application.cc:104
Time m_interval
Wait interval seconds between sending each packet.
Definition: v4traceroute.h:97
virtual void DoDispose(void)
Destructor implementation.
Definition: application.cc:83
virtual int Bind(const Address &address)=0
Allocate a local endpoint for this socket.
Every class exported by the ns3 library is enclosed in the ns3 namespace.
static InetSocketAddress ConvertFrom(const Address &address)
Returns an InetSocketAddress which corresponds to the input Address.
std::ostringstream routeIpv4
The Ipv4 address of the latest hop found.
Definition: v4traceroute.h:133
Ptr< const AttributeChecker > MakeBooleanChecker(void)
Definition: boolean.cc:121
uint16_t GetPort(void) const
uint32_t m_size
Specifies the number of data bytes to be sent.
Definition: v4traceroute.h:103
ICMP Echo header.
Definition: icmpv4.h:107
#define NS_LOG_UNCOND(msg)
Output the requested message unconditionally.
static EventId ScheduleNow(MEM mem_ptr, OBJ obj)
Schedule an event to expire Now.
Definition: simulator.h:1578
AttributeValue implementation for Ipv4Address.
Definition: ipv4-address.h:329
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:1125
static Time Now(void)
Return the current simulation virtual time.
Definition: simulator.cc:193
NS_LOG_LOGIC("Net device "<< nd<< " is not bridged")
uint16_t m_ttl
The current TTL value.
Definition: v4traceroute.h:119
uint16_t GetSequenceNumber(void) const
Get the Echo sequence number.
Definition: icmpv4.cc:179
std::ostringstream osRoute
Stream of characters used for printing a single route.
Definition: v4traceroute.h:131
Ptr< OutputStreamWrapper > printStream
Stream of the traceroute used for the output file.
Definition: v4traceroute.h:135
EventId m_next
Next packet will be sent.
Definition: v4traceroute.h:113
int64_t GetMilliSeconds(void) const
Get an approximation of the time stored in this instance in the indicated unit.
Definition: nstime.h:359
uint16_t GetIdentifier(void) const
Get the Echo identifier.
Definition: icmpv4.cc:173
void SetSequenceNumber(uint16_t seq)
Set the Echo sequence number.
Definition: icmpv4.cc:146
void GetData(uint8_t payload[8]) const
Get the ICMP carried data.
Definition: icmpv4.cc:438
#define NS_LOG_DEBUG(msg)
Use NS_LOG to output a message of level LOG_DEBUG.
Definition: log.h:272
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition: nstime.h:1062
bool IsRunning(void) const
This method is syntactic sugar for !IsExpired().
Definition: event-id.cc:65
void Cancel(void)
This method is syntactic sugar for the ns3::Simulator::Cancel method.
Definition: event-id.cc:53
uint32_t GetNApplications(void) const
Definition: node.cc:176
virtual int SendTo(Ptr< Packet > p, uint32_t flags, const Address &toAddress)=0
Send data to a specified peer.
std::map< uint16_t, Time > m_sent
All sent but not answered packets. Map icmp seqno -> when sent.
Definition: v4traceroute.h:127
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.
uint16_t m_seq
ICMP ECHO sequence number.
Definition: v4traceroute.h:107
Ptr< const AttributeAccessor > MakeIpv4AddressAccessor(T1 a1)
Create an AttributeAccessor for a class data member, or a lone class get functor or set method...
Definition: ipv4-address.h:329
uint32_t GetApplicationId(void) const
Return the application ID in the node.
virtual int Close(void)=0
Close a socket.
void SetAttribute(std::string name, const AttributeValue &value)
Set a single attribute, raising fatal errors if unsuccessful.
Definition: object-base.cc:185
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:45
void Send()
Send one (ICMP ECHO) to the destination.
a unique identifier for an interface.
Definition: type-id.h:58
TypeId SetParent(TypeId tid)
Set the parent TypeId.
Definition: type-id.cc:915
static bool IsMatchingType(const Address &address)
std::ostream * GetStream(void)
Return a pointer to an ostream previously set in the wrapper.
Traceroute application sends one ICMP ECHO request with TTL=1, and after receiving an ICMP TIME EXCEE...
Definition: v4traceroute.h:50
void AddHeader(const Header &header)
Add header to this packet.
Definition: packet.cc:256
virtual void SetIpTtl(uint8_t ipTtl)
Manually set IP Time to Live field.
Definition: socket.cc:513
static const uint8_t PROT_NUMBER
ICMP protocol number (0x1)
Ipv4Address GetIpv4(void) const
static TypeId LookupByName(std::string name)
Get a TypeId by name.
Definition: type-id.cc:824
virtual uint32_t GetRxAvailable(void) const =0
Return number of bytes which can be returned from one or multiple calls to Recv.
virtual void StartApplication(void)
Application specific startup code.
void Print(Ptr< OutputStreamWrapper > stream)
Prints the application traced routes into a given OutputStream.
uint32_t m_probeCount
The Current probe value.
Definition: v4traceroute.h:115