A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
ipv4-global-routing.cc
Go to the documentation of this file.
1//
2// Copyright (c) 2008 University of Washington
3//
4// SPDX-License-Identifier: GPL-2.0-only
5//
6
8
10#include "ipv4-route.h"
12
13#include "ns3/boolean.h"
14#include "ns3/log.h"
15#include "ns3/names.h"
16#include "ns3/net-device.h"
17#include "ns3/node.h"
18#include "ns3/object.h"
19#include "ns3/packet.h"
20#include "ns3/simulator.h"
21
22#include <iomanip>
23#include <vector>
24
25namespace ns3
26{
27
28NS_LOG_COMPONENT_DEFINE("Ipv4GlobalRouting");
29
30NS_OBJECT_ENSURE_REGISTERED(Ipv4GlobalRouting);
31
32TypeId
34{
35 static TypeId tid =
36 TypeId("ns3::Ipv4GlobalRouting")
38 .SetGroupName("Internet")
39 .AddAttribute("RandomEcmpRouting",
40 "Set to true if packets are randomly routed among ECMP; set to false for "
41 "using only one route consistently",
42 BooleanValue(false),
45 .AddAttribute("RespondToInterfaceEvents",
46 "Set to true if you want to dynamically recompute the global routes upon "
47 "Interface notification events (up/down, or add/remove address)",
48 BooleanValue(false),
51 return tid;
52}
53
55 : m_randomEcmpRouting(false),
56 m_respondToInterfaceEvents(false)
57{
58 NS_LOG_FUNCTION(this);
59
61}
62
67
68void
70{
71 NS_LOG_FUNCTION(this << dest << nextHop << interface);
72 auto route = new Ipv4RoutingTableEntry();
73 *route = Ipv4RoutingTableEntry::CreateHostRouteTo(dest, nextHop, interface);
74 m_hostRoutes.push_back(route);
75}
76
77void
79{
80 NS_LOG_FUNCTION(this << dest << interface);
81 auto route = new Ipv4RoutingTableEntry();
82 *route = Ipv4RoutingTableEntry::CreateHostRouteTo(dest, interface);
83 m_hostRoutes.push_back(route);
84}
85
86void
88 Ipv4Mask networkMask,
89 Ipv4Address nextHop,
90 uint32_t interface)
91{
92 NS_LOG_FUNCTION(this << network << networkMask << nextHop << interface);
93 auto route = new Ipv4RoutingTableEntry();
94 *route = Ipv4RoutingTableEntry::CreateNetworkRouteTo(network, networkMask, nextHop, interface);
95 m_networkRoutes.push_back(route);
96}
97
98void
100{
101 NS_LOG_FUNCTION(this << network << networkMask << interface);
102 auto route = new Ipv4RoutingTableEntry();
103 *route = Ipv4RoutingTableEntry::CreateNetworkRouteTo(network, networkMask, interface);
104 m_networkRoutes.push_back(route);
105}
106
107void
109 Ipv4Mask networkMask,
110 Ipv4Address nextHop,
111 uint32_t interface)
112{
113 NS_LOG_FUNCTION(this << network << networkMask << nextHop << interface);
114 auto route = new Ipv4RoutingTableEntry();
115 *route = Ipv4RoutingTableEntry::CreateNetworkRouteTo(network, networkMask, nextHop, interface);
116 m_ASexternalRoutes.push_back(route);
117}
118
121{
122 NS_LOG_FUNCTION(this << dest << oif);
123 NS_LOG_LOGIC("Looking for route for destination " << dest);
124 Ptr<Ipv4Route> rtentry = nullptr;
125 // store all available routes that bring packets to their destination
126 typedef std::vector<Ipv4RoutingTableEntry*> RouteVec_t;
127 RouteVec_t allRoutes;
128
129 NS_LOG_LOGIC("Number of m_hostRoutes = " << m_hostRoutes.size());
130 for (auto i = m_hostRoutes.begin(); i != m_hostRoutes.end(); i++)
131 {
132 NS_ASSERT((*i)->IsHost());
133 if ((*i)->GetDest() == dest)
134 {
135 if (oif)
136 {
137 if (oif != m_ipv4->GetNetDevice((*i)->GetInterface()))
138 {
139 NS_LOG_LOGIC("Not on requested interface, skipping");
140 continue;
141 }
142 }
143 allRoutes.push_back(*i);
144 NS_LOG_LOGIC(allRoutes.size() << "Found global host route" << *i);
145 }
146 }
147 if (allRoutes.empty()) // if no host route is found
148 {
149 NS_LOG_LOGIC("Number of m_networkRoutes" << m_networkRoutes.size());
150 for (auto j = m_networkRoutes.begin(); j != m_networkRoutes.end(); j++)
151 {
152 Ipv4Mask mask = (*j)->GetDestNetworkMask();
153 Ipv4Address entry = (*j)->GetDestNetwork();
154 if (mask.IsMatch(dest, entry))
155 {
156 if (oif)
157 {
158 if (oif != m_ipv4->GetNetDevice((*j)->GetInterface()))
159 {
160 NS_LOG_LOGIC("Not on requested interface, skipping");
161 continue;
162 }
163 }
164 allRoutes.push_back(*j);
165 NS_LOG_LOGIC(allRoutes.size() << "Found global network route" << *j);
166 }
167 }
168 }
169 if (allRoutes.empty()) // consider external if no host/network found
170 {
171 for (auto k = m_ASexternalRoutes.begin(); k != m_ASexternalRoutes.end(); k++)
172 {
173 Ipv4Mask mask = (*k)->GetDestNetworkMask();
174 Ipv4Address entry = (*k)->GetDestNetwork();
175 if (mask.IsMatch(dest, entry))
176 {
177 NS_LOG_LOGIC("Found external route" << *k);
178 if (oif)
179 {
180 if (oif != m_ipv4->GetNetDevice((*k)->GetInterface()))
181 {
182 NS_LOG_LOGIC("Not on requested interface, skipping");
183 continue;
184 }
185 }
186 allRoutes.push_back(*k);
187 break;
188 }
189 }
190 }
191 if (!allRoutes.empty()) // if route(s) is found
192 {
193 // pick up one of the routes uniformly at random if random
194 // ECMP routing is enabled, or always select the first route
195 // consistently if random ECMP routing is disabled
196 uint32_t selectIndex;
198 {
199 selectIndex = m_rand->GetInteger(0, allRoutes.size() - 1);
200 }
201 else
202 {
203 selectIndex = 0;
204 }
205 Ipv4RoutingTableEntry* route = allRoutes.at(selectIndex);
206 // create a Ipv4Route object from the selected routing table entry
207 rtentry = Create<Ipv4Route>();
208 rtentry->SetDestination(route->GetDest());
209 /// \todo handle multi-address case
210 rtentry->SetSource(m_ipv4->GetAddress(route->GetInterface(), 0).GetLocal());
211 rtentry->SetGateway(route->GetGateway());
212 uint32_t interfaceIdx = route->GetInterface();
213 rtentry->SetOutputDevice(m_ipv4->GetNetDevice(interfaceIdx));
214 return rtentry;
215 }
216 else
217 {
218 return nullptr;
219 }
220}
221
224{
225 NS_LOG_FUNCTION(this);
226 uint32_t n = 0;
227 n += m_hostRoutes.size();
228 n += m_networkRoutes.size();
229 n += m_ASexternalRoutes.size();
230 return n;
231}
232
235{
236 NS_LOG_FUNCTION(this << index);
237 if (index < m_hostRoutes.size())
238 {
239 uint32_t tmp = 0;
240 for (auto i = m_hostRoutes.begin(); i != m_hostRoutes.end(); i++)
241 {
242 if (tmp == index)
243 {
244 return *i;
245 }
246 tmp++;
247 }
248 }
249 index -= m_hostRoutes.size();
250 uint32_t tmp = 0;
251 if (index < m_networkRoutes.size())
252 {
253 for (auto j = m_networkRoutes.begin(); j != m_networkRoutes.end(); j++)
254 {
255 if (tmp == index)
256 {
257 return *j;
258 }
259 tmp++;
260 }
261 }
262 index -= m_networkRoutes.size();
263 tmp = 0;
264 for (auto k = m_ASexternalRoutes.begin(); k != m_ASexternalRoutes.end(); k++)
265 {
266 if (tmp == index)
267 {
268 return *k;
269 }
270 tmp++;
271 }
272 NS_ASSERT(false);
273 // quiet compiler.
274 return nullptr;
275}
276
277void
279{
280 NS_LOG_FUNCTION(this << index);
281 if (index < m_hostRoutes.size())
282 {
283 uint32_t tmp = 0;
284 for (auto i = m_hostRoutes.begin(); i != m_hostRoutes.end(); i++)
285 {
286 if (tmp == index)
287 {
288 NS_LOG_LOGIC("Removing route " << index << "; size = " << m_hostRoutes.size());
289 delete *i;
290 m_hostRoutes.erase(i);
291 NS_LOG_LOGIC("Done removing host route "
292 << index << "; host route remaining size = " << m_hostRoutes.size());
293 return;
294 }
295 tmp++;
296 }
297 }
298 index -= m_hostRoutes.size();
299 uint32_t tmp = 0;
300 for (auto j = m_networkRoutes.begin(); j != m_networkRoutes.end(); j++)
301 {
302 if (tmp == index)
303 {
304 NS_LOG_LOGIC("Removing route " << index << "; size = " << m_networkRoutes.size());
305 delete *j;
306 m_networkRoutes.erase(j);
307 NS_LOG_LOGIC("Done removing network route "
308 << index << "; network route remaining size = " << m_networkRoutes.size());
309 return;
310 }
311 tmp++;
312 }
313 index -= m_networkRoutes.size();
314 tmp = 0;
315 for (auto k = m_ASexternalRoutes.begin(); k != m_ASexternalRoutes.end(); k++)
316 {
317 if (tmp == index)
318 {
319 NS_LOG_LOGIC("Removing route " << index << "; size = " << m_ASexternalRoutes.size());
320 delete *k;
321 m_ASexternalRoutes.erase(k);
322 NS_LOG_LOGIC("Done removing network route "
323 << index << "; network route remaining size = " << m_networkRoutes.size());
324 return;
325 }
326 tmp++;
327 }
328 NS_ASSERT(false);
329}
330
331int64_t
333{
334 NS_LOG_FUNCTION(this << stream);
335 m_rand->SetStream(stream);
336 return 1;
337}
338
339void
341{
342 NS_LOG_FUNCTION(this);
343 for (auto i = m_hostRoutes.begin(); i != m_hostRoutes.end(); i = m_hostRoutes.erase(i))
344 {
345 delete (*i);
346 }
347 for (auto j = m_networkRoutes.begin(); j != m_networkRoutes.end(); j = m_networkRoutes.erase(j))
348 {
349 delete (*j);
350 }
351 for (auto l = m_ASexternalRoutes.begin(); l != m_ASexternalRoutes.end();
352 l = m_ASexternalRoutes.erase(l))
353 {
354 delete (*l);
355 }
356
358}
359
360// Formatted like output of "route -n" command
361void
363{
364 NS_LOG_FUNCTION(this << stream);
365 std::ostream* os = stream->GetStream();
366 // Copy the current ostream state
367 std::ios oldState(nullptr);
368 oldState.copyfmt(*os);
369
370 *os << std::resetiosflags(std::ios::adjustfield) << std::setiosflags(std::ios::left);
371
372 *os << "Node: " << m_ipv4->GetObject<Node>()->GetId() << ", Time: " << Now().As(unit)
373 << ", Local time: " << m_ipv4->GetObject<Node>()->GetLocalTime().As(unit)
374 << ", Ipv4GlobalRouting table" << std::endl;
375
376 if (GetNRoutes() > 0)
377 {
378 *os << "Destination Gateway Genmask Flags Metric Ref Use Iface"
379 << std::endl;
380 for (uint32_t j = 0; j < GetNRoutes(); j++)
381 {
382 std::ostringstream dest;
383 std::ostringstream gw;
384 std::ostringstream mask;
385 std::ostringstream flags;
387 dest << route.GetDest();
388 *os << std::setw(16) << dest.str();
389 gw << route.GetGateway();
390 *os << std::setw(16) << gw.str();
391 mask << route.GetDestNetworkMask();
392 *os << std::setw(16) << mask.str();
393 flags << "U";
394 if (route.IsHost())
395 {
396 flags << "H";
397 }
398 else if (route.IsGateway())
399 {
400 flags << "G";
401 }
402 *os << std::setw(6) << flags.str();
403 // Metric not implemented
404 *os << "-"
405 << " ";
406 // Ref ct not implemented
407 *os << "-"
408 << " ";
409 // Use not implemented
410 *os << "-"
411 << " ";
412 if (!Names::FindName(m_ipv4->GetNetDevice(route.GetInterface())).empty())
413 {
415 }
416 else
417 {
418 *os << route.GetInterface();
419 }
420 *os << std::endl;
421 }
422 }
423 *os << std::endl;
424 // Restore the previous ostream state
425 (*os).copyfmt(oldState);
426}
427
430 const Ipv4Header& header,
431 Ptr<NetDevice> oif,
432 Socket::SocketErrno& sockerr)
433{
434 NS_LOG_FUNCTION(this << p << &header << oif << &sockerr);
435 //
436 // First, see if this is a multicast packet we have a route for. If we
437 // have a route, then send the packet down each of the specified interfaces.
438 //
439 if (header.GetDestination().IsMulticast())
440 {
441 NS_LOG_LOGIC("Multicast destination-- returning false");
442 return nullptr; // Let other routing protocols try to handle this
443 }
444 //
445 // See if this is a unicast packet we have a route for.
446 //
447 NS_LOG_LOGIC("Unicast destination- looking up");
448 Ptr<Ipv4Route> rtentry = LookupGlobal(header.GetDestination(), oif);
449 if (rtentry)
450 {
451 sockerr = Socket::ERROR_NOTERROR;
452 }
453 else
454 {
456 }
457 return rtentry;
458}
459
460bool
462 const Ipv4Header& header,
464 const UnicastForwardCallback& ucb,
465 const MulticastForwardCallback& mcb,
466 const LocalDeliverCallback& lcb,
467 const ErrorCallback& ecb)
468{
469 NS_LOG_FUNCTION(this << p << header << header.GetSource() << header.GetDestination() << idev
470 << &lcb << &ecb);
471 // Check if input device supports IP
474
475 if (m_ipv4->IsDestinationAddress(header.GetDestination(), iif))
476 {
477 if (!lcb.IsNull())
478 {
479 NS_LOG_LOGIC("Local delivery to " << header.GetDestination());
480 lcb(p, header, iif);
481 return true;
482 }
483 else
484 {
485 // The local delivery callback is null. This may be a multicast
486 // or broadcast packet, so return false so that another
487 // multicast routing protocol can handle it. It should be possible
488 // to extend this to explicitly check whether it is a unicast
489 // packet, and invoke the error callback if so
490 return false;
491 }
492 }
493
494 // Check if input device supports IP forwarding
495 if (!m_ipv4->IsForwarding(iif))
496 {
497 NS_LOG_LOGIC("Forwarding disabled for this interface");
498 ecb(p, header, Socket::ERROR_NOROUTETOHOST);
499 return true;
500 }
501 // Next, try to find a route
502 NS_LOG_LOGIC("Unicast destination- looking up global route");
503 Ptr<Ipv4Route> rtentry = LookupGlobal(header.GetDestination());
504 if (rtentry)
505 {
506 NS_LOG_LOGIC("Found unicast destination- calling unicast callback");
507 ucb(rtentry, p, header);
508 return true;
509 }
510 else
511 {
512 NS_LOG_LOGIC("Did not find unicast destination- returning false");
513 return false; // Let other routing protocols try to handle this
514 // route request.
515 }
516}
517
518void
529
530void
541
542void
544{
545 NS_LOG_FUNCTION(this << interface << address);
546 if (m_respondToInterfaceEvents && Simulator::Now().GetSeconds() > 0) // avoid startup events
547 {
551 }
552}
553
554void
565
566void
568{
569 NS_LOG_FUNCTION(this << ipv4);
570 NS_ASSERT(!m_ipv4 && ipv4);
571 m_ipv4 = ipv4;
572}
573
574} // namespace ns3
bool IsNull() const
Check for null implementation.
Definition callback.h:555
static void DeleteGlobalRoutes()
Delete all static routes on all nodes that have a GlobalRouterInterface.
static void InitializeRoutes()
Compute routes using a Dijkstra SPF computation and populate per-node forwarding tables.
static void BuildGlobalRoutingDatabase()
Build the routing database by gathering Link State Advertisements from each node exporting a GlobalRo...
Ipv4 addresses are stored in host order in this class.
bool IsMulticast() const
void AddHostRouteTo(Ipv4Address dest, Ipv4Address nextHop, uint32_t interface)
Add a host route to the global routing table.
bool RouteInput(Ptr< const Packet > p, const Ipv4Header &header, Ptr< const NetDevice > idev, const UnicastForwardCallback &ucb, const MulticastForwardCallback &mcb, const LocalDeliverCallback &lcb, const ErrorCallback &ecb) override
Route an input packet (to be forwarded or locally delivered)
void AddASExternalRouteTo(Ipv4Address network, Ipv4Mask networkMask, Ipv4Address nextHop, uint32_t interface)
Add an external route to the global routing table.
Ipv4RoutingTableEntry * GetRoute(uint32_t i) const
Get a route from the global unicast routing table.
static TypeId GetTypeId()
Get the type ID.
void DoDispose() override
Destructor implementation.
int64_t AssignStreams(int64_t stream)
Assign a fixed random variable stream number to the random variables used by this model.
Ptr< UniformRandomVariable > m_rand
A uniform random number generator for randomly routing packets among ECMP.
void RemoveRoute(uint32_t i)
Remove a route from the global unicast routing table.
void NotifyInterfaceDown(uint32_t interface) override
void NotifyInterfaceUp(uint32_t interface) override
void SetIpv4(Ptr< Ipv4 > ipv4) override
void PrintRoutingTable(Ptr< OutputStreamWrapper > stream, Time::Unit unit=Time::S) const override
Print the Routing Table entries.
uint32_t GetNRoutes() const
Get the number of individual unicast routes that have been added to the routing table.
Ipv4GlobalRouting()
Construct an empty Ipv4GlobalRouting routing protocol,.
Ptr< Ipv4 > m_ipv4
associated IPv4 instance
Ptr< Ipv4Route > RouteOutput(Ptr< Packet > p, const Ipv4Header &header, Ptr< NetDevice > oif, Socket::SocketErrno &sockerr) override
Query routing cache for an existing route, for an outbound packet.
void AddNetworkRouteTo(Ipv4Address network, Ipv4Mask networkMask, Ipv4Address nextHop, uint32_t interface)
Add a network route to the global routing table.
void NotifyRemoveAddress(uint32_t interface, Ipv4InterfaceAddress address) override
ASExternalRoutes m_ASexternalRoutes
External routes imported.
HostRoutes m_hostRoutes
Routes to hosts.
bool m_respondToInterfaceEvents
Set to true if this interface should respond to interface events by globally recomputing routes.
void NotifyAddAddress(uint32_t interface, Ipv4InterfaceAddress address) override
bool m_randomEcmpRouting
Set to true if packets are randomly routed among ECMP; set to false for using only one route consiste...
NetworkRoutes m_networkRoutes
Routes to networks.
Ptr< Ipv4Route > LookupGlobal(Ipv4Address dest, Ptr< NetDevice > oif=nullptr)
Lookup in the forwarding table for destination.
Packet header for IPv4.
Definition ipv4-header.h:23
Ipv4Address GetSource() const
Ipv4Address GetDestination() const
virtual bool IsForwarding(uint32_t interface) const =0
virtual Ipv4InterfaceAddress GetAddress(uint32_t interface, uint32_t addressIndex) const =0
Because addresses can be removed, the addressIndex is not guaranteed to be static across calls to thi...
virtual Ptr< NetDevice > GetNetDevice(uint32_t interface)=0
virtual bool IsDestinationAddress(Ipv4Address address, uint32_t iif) const =0
Determine whether address and interface corresponding to received packet can be accepted for local de...
virtual int32_t GetInterfaceForDevice(Ptr< const NetDevice > device) const =0
a class to store IPv4 address information on an interface
Ipv4Address GetLocal() const
Get the local address.
a class to represent an Ipv4 address mask
bool IsMatch(Ipv4Address a, Ipv4Address b) const
A record of an IPv4 routing table entry for Ipv4GlobalRouting and Ipv4StaticRouting.
Ipv4Address GetDest() const
Ipv4Address GetGateway() const
bool IsHost() const
bool IsGateway() const
uint32_t GetInterface() const
static Ipv4RoutingTableEntry CreateNetworkRouteTo(Ipv4Address network, Ipv4Mask networkMask, Ipv4Address nextHop, uint32_t interface)
static Ipv4RoutingTableEntry CreateHostRouteTo(Ipv4Address dest, Ipv4Address nextHop, uint32_t interface)
Ipv4Mask GetDestNetworkMask() const
static std::string FindName(Ptr< Object > object)
Given a pointer to an object, look to see if that object has a name associated with it and,...
Definition names.cc:818
A network Node.
Definition node.h:46
A base class which provides memory management and object aggregation.
Definition object.h:78
Ptr< T > GetObject() const
Get a pointer to the requested aggregated Object.
Definition object.h:511
virtual void DoDispose()
Destructor implementation.
Definition object.cc:433
Smart pointer class similar to boost::intrusive_ptr.
static Time Now()
Return the current simulation virtual time.
Definition simulator.cc:197
SocketErrno
Enumeration of the possible errors returned by a socket.
Definition socket.h:73
@ ERROR_NOROUTETOHOST
Definition socket.h:84
@ ERROR_NOTERROR
Definition socket.h:74
TimeWithUnit As(const Unit unit=Time::AUTO) const
Attach a unit to a Time, to facilitate output in a specific unit.
Definition time.cc:404
Unit
The unit to use to interpret a number representing time.
Definition nstime.h:100
a unique identifier for an interface.
Definition type-id.h:48
TypeId SetParent(TypeId tid)
Set the parent TypeId.
Definition type-id.cc:1001
#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_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition log.h:191
#define NS_LOG_LOGIC(msg)
Use NS_LOG to output a message of level LOG_LOGIC.
Definition log.h:271
#define NS_LOG_FUNCTION(parameters)
If log level LOG_FUNCTION is enabled, this macro will output all input parameters separated by ",...
Ptr< T > CreateObject(Args &&... args)
Create an object by type, with varying number of constructor parameters.
Definition object.h:619
#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 Now()
create an ns3::Time instance which contains the current simulation time.
Definition simulator.cc:294
Every class exported by the ns3 library is enclosed in the ns3 namespace.
Ptr< const AttributeChecker > MakeBooleanChecker()
Definition boolean.cc:113
Ptr< const AttributeAccessor > MakeBooleanAccessor(T1 a1)
Definition boolean.h:70