A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
ping-example.cc
Go to the documentation of this file.
1/*
2 * Copyright (c) 2022 Chandrakant Jena
3 *
4 * SPDX-License-Identifier: GPL-2.0-only
5 *
6 * Author: Chandrakant Jena <chandrakant.barcelona@gmail.com>
7 */
8
9/**
10 * @file
11 * Example to demonstrate the working of the Ping Application
12 * Network topology:
13 * @verbatim
14 A ------------------------------ B ------------------------------ C
15 100 Mbps 100 Mbps
16 5 ms (one way) 5 ms (one way)
17 IPv4 addresses:
18 10.1.1.1 <-> 10.1.1.2 / 10.1.2.1 <-> 10.1.2.2
19
20 IPv6 addresses:
21 2001:1::200:ff:fe00:1
22 <-> 2001:1::200:ff:fe00:2 / 2001:1:0:1:200:ff:fe00:3
23 <-> 2001:1:0:1:200:ff:fe00:4
24 @endverbatim
25 *
26 * The topology has three nodes interconnected by two point-to-point links.
27 * Each link has 5 ms one-way delay, for a round-trip propagation delay
28 * of 20 ms. The transmission rate on each link is 100 Mbps. The routing
29 * between links is enabled by ns-3's NixVector routing.
30 *
31 * By default, this program will send 5 pings from node A to node C using IPv6.
32 * When using IPv6, the output will look like this:
33 * @verbatim
34 PING 2001:1:0:1:200:ff:fe00:4 - 56 bytes of data; 104 bytes including ICMP and IPv6 headers.
35 64 bytes from (2001:1:0:1:200:ff:fe00:4): icmp_seq=0 ttl=63 time=20.033 ms
36 64 bytes from (2001:1:0:1:200:ff:fe00:4): icmp_seq=1 ttl=63 time=20.033 ms
37 64 bytes from (2001:1:0:1:200:ff:fe00:4): icmp_seq=2 ttl=63 time=20.033 ms
38 64 bytes from (2001:1:0:1:200:ff:fe00:4): icmp_seq=3 ttl=63 time=20.033 ms
39 64 bytes from (2001:1:0:1:200:ff:fe00:4): icmp_seq=4 ttl=63 time=20.033 ms
40 --- 2001:1:0:1:200:ff:fe00:4 ping statistics ---
41 5 packets transmitted, 5 received, 0% packet loss, time 4020ms
42 rtt min/avg/max/mdev = 20/20/20/0 ms
43 @endverbatim
44 *
45 * When using IPv4, the output will look like this:
46 * @verbatim
47 PING 10.1.2.2 - 56 bytes of data; 84 bytes including ICMP and IPv4 headers.
48 64 bytes from (10.1.2.2): icmp_seq=0 ttl=63 time=20.027 ms
49 64 bytes from (10.1.2.2): icmp_seq=1 ttl=63 time=20.027 ms
50 64 bytes from (10.1.2.2): icmp_seq=2 ttl=63 time=20.027 ms
51 64 bytes from (10.1.2.2): icmp_seq=3 ttl=63 time=20.027 ms
52 64 bytes from (10.1.2.2): icmp_seq=4 ttl=63 time=20.027 ms
53 --- 10.1.2.2 ping statistics ---
54 5 packets transmitted, 5 received, 0% packet loss, time 4020ms
55 rtt min/avg/max/mdev = 20/20/20/0 ms
56 @endverbatim
57 *
58 * The example program will also produce four pcap traces (one for each
59 * NetDevice in the scenario) that can be viewed using tcpdump or Wireshark.
60 *
61 * Other program options include options to change the destination and
62 * source addresses, number of packets (count), packet size, interval,
63 * and whether to enable logging (if logging is enabled in the build).
64 *
65 * The Ping application in this example starts at simulation time 1 and will
66 * stop either at simulation time 50 or once 'Count' pings have been responded
67 * to, whichever comes first.
68 */
69
70#include "ns3/core-module.h"
71#include "ns3/internet-apps-module.h"
72#include "ns3/internet-module.h"
73#include "ns3/network-module.h"
74#include "ns3/nix-vector-routing-module.h"
75#include "ns3/point-to-point-module.h"
76
77#include <fstream>
78#include <optional>
79
80using namespace ns3;
81
82NS_LOG_COMPONENT_DEFINE("PingExample");
83
84int
85main(int argc, char* argv[])
86{
87 bool logging{false};
88 Time interPacketInterval{Seconds(1)};
89 uint32_t size{56};
90 uint32_t count{5};
91 std::string destinationStr;
92 Address destination;
93 std::string sourceStr;
94 Address source;
95 bool useIpv6{true};
96 std::optional<Ipv4Address> v4Dst;
97 std::optional<Ipv6Address> v6Dst;
98 std::optional<Ipv4Address> v4Src;
99 std::optional<Ipv6Address> v6Src;
100
101 GlobalValue::Bind("ChecksumEnabled", BooleanValue(true));
102
103 CommandLine cmd(__FILE__);
104 cmd.AddValue("logging", "Tell application to log if true", logging);
105 cmd.AddValue("interval", "The time to wait between two packets", interPacketInterval);
106 cmd.AddValue("size", "Data bytes to be sent, per-packet", size);
107 cmd.AddValue("count", "Number of packets to be sent", count);
108 cmd.AddValue("destination",
109 "Destination IPv4 or IPv6 address, e.g., \"10.1.2.2\"",
110 destinationStr);
111 cmd.AddValue("source",
112 "Source address, needed only for multicast or broadcast destinations",
113 sourceStr);
114 cmd.Parse(argc, argv);
115
116 if (!destinationStr.empty())
117 {
118 if (Ipv4Address::CheckCompatible(destinationStr))
119 {
120 v4Dst = Ipv4Address(destinationStr.c_str());
121 useIpv6 = false;
122 destination = v4Dst.value();
123 }
124 else if (Ipv6Address::CheckCompatible(destinationStr))
125 {
126 v6Dst = Ipv6Address(destinationStr.c_str());
127 useIpv6 = true;
128 destination = v6Dst.value();
129 }
130 else
131 {
132 NS_ABORT_MSG("Can't parse destination address " << destinationStr);
133 }
134 }
135
136 if (!sourceStr.empty())
137 {
138 if (Ipv4Address::CheckCompatible(sourceStr))
139 {
140 v4Src = Ipv4Address(sourceStr.c_str());
141 useIpv6 = false;
142 source = v4Src.value();
143 }
144 else if (Ipv6Address::CheckCompatible(sourceStr))
145 {
146 v6Src = Ipv6Address(sourceStr.c_str());
147 useIpv6 = true;
148 source = v6Src.value();
149 }
150 else
151 {
152 NS_ABORT_MSG("Can't parse destination address " << destinationStr);
153 }
154 }
155 if (sourceStr.empty())
156 {
157 if (useIpv6)
158 {
159 if (v6Dst && v6Dst->IsMulticast())
160 {
161 std::cout << "Specify a source address to use when pinging multicast addresses"
162 << std::endl;
163 std::cout << "Program exiting..." << std::endl;
164 return 0;
165 }
166 }
167 else
168 {
169 if (v4Dst && (v4Dst->IsBroadcast() || v4Dst->IsMulticast()))
170 {
171 std::cout << "Specify a source address to use when pinging broadcast or multicast "
172 "addresses"
173 << std::endl;
174 std::cout << "Program exiting..." << std::endl;
175 return 0;
176 }
177 }
178 }
179
180 if (logging)
181 {
184 }
185
187 nodes.Create(3);
188 NodeContainer link1Nodes;
189 link1Nodes.Add(nodes.Get(0));
190 link1Nodes.Add(nodes.Get(1));
191 NodeContainer link2Nodes;
192 link2Nodes.Add(nodes.Get(1));
193 link2Nodes.Add(nodes.Get(2));
194
196 pointToPoint.SetDeviceAttribute("DataRate", StringValue("100Mbps"));
197 pointToPoint.SetChannelAttribute("Delay", StringValue("5ms"));
198
199 NetDeviceContainer link1Devices;
200 link1Devices = pointToPoint.Install(link1Nodes);
201 NetDeviceContainer link2Devices;
202 link2Devices = pointToPoint.Install(link2Nodes);
203
204 // The following block of code inserts an optional packet loss model
207 std::list<uint32_t> dropList;
208 // Enable one or more of the below lines to force specific packet losses
209 // dropList.push_back (0);
210 // dropList.push_back (1);
211 // dropList.push_back (2);
212 // dropList.push_back (3);
213 // dropList.push_back (4);
214 // etc. (other lines may be added)
215 errorModel->SetList(dropList);
216 p2pSender->SetReceiveErrorModel(errorModel);
217
218 if (!useIpv6)
219 {
222 stack.SetRoutingHelper(nixRouting);
223 stack.SetIpv6StackInstall(false);
224 stack.Install(nodes);
225
226 Ipv4AddressHelper addressV4;
227 addressV4.SetBase("10.1.1.0", "255.255.255.0");
228 addressV4.Assign(link1Devices);
229 addressV4.NewNetwork();
230 Ipv4InterfaceContainer link2InterfacesV4 = addressV4.Assign(link2Devices);
231
232 if (destination.IsInvalid())
233 {
234 destination = link2InterfacesV4.GetAddress(1, 0);
235 }
236 }
237 else
238 {
241 stack.SetRoutingHelper(nixRouting);
242 stack.SetIpv4StackInstall(false);
243 stack.Install(nodes);
244
245 Ipv6AddressHelper addressV6;
246 addressV6.SetBase("2001:1::", 64);
247 addressV6.Assign(link1Devices);
248 addressV6.NewNetwork();
249 Ipv6InterfaceContainer link2InterfacesV6 = addressV6.Assign(link2Devices);
250
251 if (destination.IsInvalid())
252 {
253 destination = link2InterfacesV6.GetAddress(1, 1);
254 }
255 }
256
257 // Create Ping application and installing on node A
258 PingHelper pingHelper(destination, source);
259 pingHelper.SetAttribute("Interval", TimeValue(interPacketInterval));
260 pingHelper.SetAttribute("Size", UintegerValue(size));
261 pingHelper.SetAttribute("Count", UintegerValue(count));
262 ApplicationContainer apps = pingHelper.Install(nodes.Get(0));
263 apps.Start(Seconds(1));
264 apps.Stop(Seconds(50));
265
266 pointToPoint.EnablePcapAll("ping-example");
267
271 return 0;
272}
a polymophic address class
Definition address.h:114
bool IsInvalid() const
Definition address.cc:55
holds a vector of ns3::Application pointers.
void Start(Time start) const
Start all of the Applications in this container at the start time given as a parameter.
void Stop(Time stop) const
Arrange for all of the Applications in this container to Stop() at the Time given as a parameter.
AttributeValue implementation for Boolean.
Definition boolean.h:26
Parse command-line arguments.
static void Bind(std::string name, const AttributeValue &value)
Iterate over the set of GlobalValues until a matching name is found and then set its value with Globa...
aggregate IP/TCP/UDP functionality to existing Nodes.
A helper class to make life easier while doing simple IPv4 address assignment in scripts.
void SetBase(Ipv4Address network, Ipv4Mask mask, Ipv4Address base="0.0.0.1")
Set the base network number, network mask and base address.
Ipv4Address NewNetwork()
Increment the network number and reset the IP address counter to the base value provided in the SetBa...
Ipv4InterfaceContainer Assign(const NetDeviceContainer &c)
Assign IP addresses to the net devices specified in the container based on the current network prefix...
Ipv4 addresses are stored in host order in this class.
static bool CheckCompatible(const std::string &addressStr)
Checks if the string contains an Ipv4Address.
holds a vector of std::pair of Ptr<Ipv4> and interface index.
Ipv4Address GetAddress(uint32_t i, uint32_t j=0) const
Helper class to auto-assign global IPv6 unicast addresses.
void SetBase(Ipv6Address network, Ipv6Prefix prefix, Ipv6Address base=Ipv6Address("::1"))
Set the base network number, network prefix, and base interface ID.
void NewNetwork()
Allocate a new network.
Ipv6InterfaceContainer Assign(const NetDeviceContainer &c)
Allocate an Ipv6InterfaceContainer with auto-assigned addresses.
Describes an IPv6 address.
static bool CheckCompatible(const std::string &addressStr)
Checks if the string contains an Ipv6Address.
Keep track of a set of IPv6 interfaces.
Ipv6Address GetAddress(uint32_t i, uint32_t j) const
Get the address for the specified index.
holds a vector of ns3::NetDevice pointers
Ptr< NetDevice > Get(uint32_t i) const
Get the Ptr<NetDevice> stored in this container at a given index.
keep track of a set of node pointers.
void Add(const NodeContainer &nc)
Append the contents of another NodeContainer to the end of this container.
Create a ping application and associate it to a node.
Definition ping-helper.h:31
Build a set of PointToPointNetDevice objects.
Smart pointer class similar to boost::intrusive_ptr.
Definition ptr.h:70
static void Destroy()
Execute the events scheduled with ScheduleDestroy().
Definition simulator.cc:131
static void Run()
Run the simulation.
Definition simulator.cc:167
static void Stop()
Tell the Simulator the calling event should be the last one executed.
Definition simulator.cc:175
Hold variables of type string.
Definition string.h:45
Simulation virtual time values and global simulation resolution.
Definition nstime.h:96
AttributeValue implementation for Time.
Definition nstime.h:1483
Hold an unsigned integer type.
Definition uinteger.h:34
#define NS_ABORT_MSG(msg)
Unconditional abnormal program termination with a message.
Definition abort.h:38
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition log.h:194
NixVectorHelper< Ipv6RoutingHelper > Ipv6NixVectorHelper
Create the typedef Ipv6NixVectorHelper with T as Ipv6RoutingHelper.
NixVectorHelper< Ipv4RoutingHelper > Ipv4NixVectorHelper
Create the typedef Ipv4NixVectorHelper with T as Ipv4RoutingHelper.
Ptr< T > CreateObject(Args &&... args)
Create an object by type, with varying number of constructor parameters.
Definition object.h:627
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition nstime.h:1381
NodeContainer nodes
pointToPoint
Definition first.py:27
stack
Definition first.py:33
Every class exported by the ns3 library is enclosed in the ns3 namespace.
void LogComponentEnable(const std::string &name, LogLevel level)
Enable the logging output associated with that log component.
Definition log.cc:284
Ptr< T1 > DynamicCast(const Ptr< T2 > &p)
Cast a Ptr.
Definition ptr.h:605
LogLevel
Logging severity classes and levels.
Definition log.h:86
@ LOG_LEVEL_ALL
Print everything.
Definition log.h:108
@ LOG_PREFIX_TIME
Prefix all trace prints with simulation time.
Definition log.h:111
@ LOG_PREFIX_NODE
Prefix all trace prints with simulation node.
Definition log.h:112
void LogComponentEnableAll(LogLevel level)
Enable the logging output for all registered log components.
Definition log.cc:302