A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
fd-tap-ping.cc
Go to the documentation of this file.
1/*
2 * Copyright (c) 2012 University of Washington, 2012 INRIA
3 *
4 * SPDX-License-Identifier: GPL-2.0-only
5 */
6
7// Allow ns-3 to ping a real host somewhere, using emulation mode and ping
8// the simulated node from the host.
9//
10// +-------------------------------------+
11// | host |
12// +-------------------------------------+
13// | ns-3 simulation | |
14// +----------------------+ |
15// | ns-3 Node | |
16// | +----------------+ | |
17// | | ns-3 TCP | | |
18// | +----------------+ | |
19// | | ns-3 IPv4 | | |
20// | +----------------+ | |
21// | | FdNetDevice | | |
22// |--+----------------+--+ +------+ |
23// | | TAP | | eth0 | |
24// | +------+ +------+ |
25// | 1.2.3.4 | |
26// +-------------------------------|-----+
27// |
28// | +-------------+
29// ------------ (Internet) ----- | Remote host |
30// +-------------+
31//
32// To use this example:
33// 1) ns-3 will create the TAP device for you in the host machine.
34// For this you need to provide the network address to allocate IP addresses
35// for the TAP device and the ns-3 FdNetDevice.
36//
37// 2) Take into consideration that this experiment requires the host to be able
38// to forward traffic generated by the simulation to the Internet.
39// So for Linux systems, make sure to configure:
40// # echo 1 > /proc/sys/net/ipv4/ip_forward
41//
42// Also enable natting so the ICMP replies from the remote host can reach
43// back the TAP.
44// - TAP-network-address is the same as 'tapNetwork'
45// - TAP-network-mask is the same as 'tapMask'
46// # iptables -t nat -A POSTROUTING -s <TAP-network-address>/<TAP-network-mask> -j MASQUERADE
47//
48// 3) Before running the example make sure that the tap creator binary has root suid.
49// If the --enable-sudo option was used to configure ns-3 with ns3, then the following
50// step will not be necessary.
51//
52// # chown root.root build/src/fd-net-device/ns3-dev-tap-device-creator
53// # sudo chmod 4755 build/src/fd-net-device/ns3-dev-tap-device-creator
54//
55// 4) The example can be executed as follows using ns3:
56//
57// ./ns3 run fd-tap-ping --command-template="%s --tapNetwork=<TAP-network-address>
58// --tapMask=<TAP-network-mask>"
59//
60
61#include "ns3/abort.h"
62#include "ns3/core-module.h"
63#include "ns3/fd-net-device-module.h"
64#include "ns3/internet-apps-module.h"
65#include "ns3/internet-module.h"
66#include "ns3/ipv4-list-routing-helper.h"
67#include "ns3/ipv4-static-routing-helper.h"
68#include "ns3/network-module.h"
69
70using namespace ns3;
71
72NS_LOG_COMPONENT_DEFINE("TAPPingExample");
73
74static void
75PingRtt(std::string context, uint16_t seqNo, Time rtt)
76{
77 NS_LOG_UNCOND("Received " << seqNo << " Response with RTT = " << rtt);
78}
79
80int
81main(int argc, char* argv[])
82{
83 NS_LOG_INFO("Ping Emulation Example with TAP");
84
85 std::string deviceName("tap0");
86 std::string remote("192.0.43.10"); // example.com
87 std::string network("1.2.3.4");
88 std::string mask("255.255.255.0");
89 std::string pi("no");
90
91 //
92 // Allow the user to override any of the defaults at run-time, via
93 // command-line arguments
94 //
95 CommandLine cmd(__FILE__);
96 cmd.AddValue("deviceName", "Device name", deviceName);
97 cmd.AddValue("remote", "Remote IP address (dotted decimal only please)", remote);
98 cmd.AddValue("tapNetwork",
99 "Network address to assign the TAP device IP address (dotted decimal only please)",
100 network);
101 cmd.AddValue("tapMask",
102 "Network mask for configure the TAP device (dotted decimal only please)",
103 mask);
104 cmd.AddValue("modePi",
105 "If 'yes' a PI header will be added to the traffic traversing the device(flag "
106 "IFF_NOPI will be unset).",
107 pi);
108 cmd.Parse(argc, argv);
109
110 NS_ABORT_MSG_IF(network == "1.2.3.4",
111 "You must change the local IP address before running this example");
112
113 Ipv4Address remoteIp(remote.c_str());
114 Ipv4Address tapNetwork(network.c_str());
115 Ipv4Mask tapMask(mask.c_str());
116
117 bool modePi = (pi == "yes");
118
119 //
120 // Since we are using a real piece of hardware we need to use the realtime
121 // simulator.
122 //
123 GlobalValue::Bind("SimulatorImplementationType", StringValue("ns3::RealtimeSimulatorImpl"));
124
125 //
126 // Since we are going to be talking to real-world machines, we need to enable
127 // calculation of checksums in our protocols.
128 //
129 GlobalValue::Bind("ChecksumEnabled", BooleanValue(true));
130
131 //
132 // In such a simple topology, the use of the helper API can be a hindrance
133 // so we drop down into the low level API and do it manually.
134 //
135 // First we need a single node.
136 //
137 NS_LOG_INFO("Create Node");
139
140 // Create an fd device, set a MAC address and point the device to the
141 // Linux device name. The device needs a transmit queueing discipline so
142 // create a droptail queue and give it to the device. Finally, "install"
143 // the device into the node.
144 //
145 Ipv4AddressHelper addresses;
146 addresses.SetBase(tapNetwork, tapMask);
147 Ipv4Address tapIp = addresses.NewAddress();
148
149 NS_LOG_INFO("Create Device");
151 helper.SetDeviceName(deviceName);
152 helper.SetModePi(modePi);
153 helper.SetTapIpv4Address(tapIp);
154 helper.SetTapIpv4Mask(tapMask);
155
156 NetDeviceContainer devices = helper.Install(node);
157 Ptr<NetDevice> device = devices.Get(0);
158
159 //
160 // Add a default internet stack to the node (ARP, IPv4, ICMP, UDP and TCP).
161 //
162 NS_LOG_INFO("Add Internet Stack");
163 InternetStackHelper internetStackHelper;
164 internetStackHelper.Install(node);
165
166 //
167 // Add an address to the ns-3 device in the same network than one
168 // assigned to the TAP.
169 //
170 NS_LOG_INFO("Create IPv4 Interface");
171 Ptr<Ipv4> ipv4 = node->GetObject<Ipv4>();
172 uint32_t interface = ipv4->AddInterface(device);
173 Ipv4Address devIp = addresses.NewAddress();
175 ipv4->AddAddress(interface, address);
176 ipv4->SetMetric(interface, 1);
177 ipv4->SetUp(interface);
178
179 //
180 // Add a route to the ns-3 device so it can reach the outside world though the
181 // TAP.
182 //
183 Ipv4StaticRoutingHelper ipv4RoutingHelper;
184 Ptr<Ipv4StaticRouting> staticRouting = ipv4RoutingHelper.GetStaticRouting(ipv4);
185 staticRouting->SetDefaultRoute(tapIp, interface);
186
187 //
188 // Create the ping application. This application knows how to send
189 // ICMP echo requests. Setting up the packet sink manually is a bit
190 // of a hassle and since there is no law that says we cannot mix the
191 // helper API with the low level API, let's just use the helper.
192 //
193 NS_LOG_INFO("Create Ping Application");
195 app->SetAttribute("Destination", AddressValue(remoteIp));
196 app->SetAttribute("VerboseMode", EnumValue(Ping::VerboseMode::VERBOSE));
197 node->AddApplication(app);
198 app->SetStartTime(Seconds(1.0));
199 app->SetStopTime(Seconds(21.0));
200
201 //
202 // Give the application a name. This makes life much easier when constructing
203 // config paths.
204 //
205 Names::Add("app", app);
206
207 //
208 // Hook a trace to print something when the response comes back.
209 //
210 Config::Connect("/Names/app/Rtt", MakeCallback(&PingRtt));
211
212 //
213 // Enable a promiscuous pcap trace to see what is coming and going on our device.
214 //
215 helper.EnablePcap("fd-tap-ping", device, true);
216
217 //
218 // Now, do the actual emulation.
219 //
220 NS_LOG_INFO("Run Emulation.");
224 NS_LOG_INFO("Done.");
225
226 return 0;
227}
Parse command-line arguments.
void SetDeviceName(std::string deviceName)
Set the device name of this device.
Hold variables of type enum.
Definition enum.h:52
virtual NetDeviceContainer Install(Ptr< Node > node) const
This method creates a FdNetDevice and associates it to a node.
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.
void Install(std::string nodeName) const
Aggregate implementations of the ns3::Ipv4, ns3::Ipv6, ns3::Udp, and ns3::Tcp classes onto the provid...
A helper class to make life easier while doing simple IPv4 address assignment in scripts.
Ipv4Address NewAddress()
Increment the IP address counter used to allocate IP addresses.
void SetBase(Ipv4Address network, Ipv4Mask mask, Ipv4Address base="0.0.0.1")
Set the base network number, network mask and base address.
Ipv4 addresses are stored in host order in this class.
Access to the IPv4 forwarding table, interfaces, and configuration.
Definition ipv4.h:69
a class to store IPv4 address information on an interface
a class to represent an Ipv4 address mask
Helper class that adds ns3::Ipv4StaticRouting objects.
Ptr< Ipv4StaticRouting > GetStaticRouting(Ptr< Ipv4 > ipv4) const
Try and find the static routing protocol as either the main routing protocol or in the list of routin...
static void Add(std::string name, Ptr< Object > object)
Add the association between the string "name" and the Ptr<Object> obj.
Definition names.cc:764
holds a vector of ns3::NetDevice pointers
void EnablePcap(std::string prefix, Ptr< NetDevice > nd, bool promiscuous=false, bool explicitFilename=false)
Enable pcap output the indicated net device.
Smart pointer class similar to boost::intrusive_ptr.
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
build a set of FdNetDevice objects attached to a virtual TAP network interface
void SetTapIpv4Mask(Ipv4Mask mask)
Set the IPv4 network mask for the TAP device.
void SetTapIpv4Address(Ipv4Address address)
Set the device IPv4 address.
void SetModePi(bool pi)
Set flag IFF_NO_PI on the device.
Simulation virtual time values and global simulation resolution.
Definition nstime.h:94
static void PingRtt(std::string context, uint16_t seqNo, Time rtt)
void Connect(std::string path, const CallbackBase &cb)
Definition config.cc:967
#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_UNCOND(msg)
Output the requested message unconditionally.
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition log.h:191
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition log.h:264
Ptr< T > CreateObject(Args &&... args)
Create an object by type, with varying number of constructor parameters.
Definition object.h:619
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition nstime.h:1308
address
Definition first.py:36
devices
Definition first.py:31
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