A Discrete-Event Network Simulator
API
socket-bound-tcp-static-routing.cc
Go to the documentation of this file.
1 /*
2  * This program is free software; you can redistribute it and/or modify
3  * it under the terms of the GNU General Public License version 2 as
4  * published by the Free Software Foundation;
5  *
6  * This program is distributed in the hope that it will be useful,
7  * but WITHOUT ANY WARRANTY; without even the implied warranty of
8  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9  * GNU General Public License for more details.
10  *
11  * You should have received a copy of the GNU General Public License
12  * along with this program; if not, write to the Free Software
13  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
14  *
15  */
16 
17 /* Test program for multi-interface host, static routing
18 
19  Destination host (10.20.1.2)
20  |
21  | 10.20.1.0/24
22  DSTRTR
23  10.10.1.0/24 / \ 10.10.2.0/24
24  / \
25  Rtr1 Rtr2
26  10.1.1.0/24 | | 10.1.2.0/24
27  | /
28  \ /
29  Source
30 */
31 
32 #include "ns3/applications-module.h"
33 #include "ns3/core-module.h"
34 #include "ns3/internet-module.h"
35 #include "ns3/ipv4-list-routing-helper.h"
36 #include "ns3/ipv4-static-routing-helper.h"
37 #include "ns3/network-module.h"
38 #include "ns3/point-to-point-module.h"
39 
40 #include <cassert>
41 #include <fstream>
42 #include <iostream>
43 #include <string>
44 
45 using namespace ns3;
46 
47 NS_LOG_COMPONENT_DEFINE("SocketBoundTcpRoutingExample");
48 
49 static const uint32_t totalTxBytes = 20000;
50 static uint32_t currentTxBytes = 0;
51 static const uint32_t writeSize = 1040;
52 uint8_t data[writeSize];
53 
54 void StartFlow(Ptr<Socket>, Ipv4Address, uint16_t);
55 void WriteUntilBufferFull(Ptr<Socket>, uint32_t);
56 
57 void SendStuff(Ptr<Socket> sock, Ipv4Address dstaddr, uint16_t port);
58 void BindSock(Ptr<Socket> sock, Ptr<NetDevice> netdev);
59 void srcSocketRecv(Ptr<Socket> socket);
60 void dstSocketRecv(Ptr<Socket> socket);
61 
62 int
63 main(int argc, char* argv[])
64 {
65  // Allow the user to override any of the defaults and the above
66  // DefaultValue::Bind ()s at run-time, via command-line arguments
67  CommandLine cmd(__FILE__);
68  cmd.Parse(argc, argv);
69 
70  Ptr<Node> nSrc = CreateObject<Node>();
71  Ptr<Node> nDst = CreateObject<Node>();
72  Ptr<Node> nRtr1 = CreateObject<Node>();
73  Ptr<Node> nRtr2 = CreateObject<Node>();
74  Ptr<Node> nDstRtr = CreateObject<Node>();
75 
76  NodeContainer c = NodeContainer(nSrc, nDst, nRtr1, nRtr2, nDstRtr);
77 
79  internet.Install(c);
80 
81  // Point-to-point links
82  NodeContainer nSrcnRtr1 = NodeContainer(nSrc, nRtr1);
83  NodeContainer nSrcnRtr2 = NodeContainer(nSrc, nRtr2);
84  NodeContainer nRtr1nDstRtr = NodeContainer(nRtr1, nDstRtr);
85  NodeContainer nRtr2nDstRtr = NodeContainer(nRtr2, nDstRtr);
86  NodeContainer nDstRtrnDst = NodeContainer(nDstRtr, nDst);
87 
88  // We create the channels first without any IP addressing information
90  p2p.SetDeviceAttribute("DataRate", StringValue("5Mbps"));
91  p2p.SetChannelAttribute("Delay", StringValue("2ms"));
92  NetDeviceContainer dSrcdRtr1 = p2p.Install(nSrcnRtr1);
93  NetDeviceContainer dSrcdRtr2 = p2p.Install(nSrcnRtr2);
94  NetDeviceContainer dRtr1dDstRtr = p2p.Install(nRtr1nDstRtr);
95  NetDeviceContainer dRtr2dDstRtr = p2p.Install(nRtr2nDstRtr);
96  NetDeviceContainer dDstRtrdDst = p2p.Install(nDstRtrnDst);
97 
98  Ptr<NetDevice> SrcToRtr1 = dSrcdRtr1.Get(0);
99  Ptr<NetDevice> SrcToRtr2 = dSrcdRtr2.Get(0);
100 
101  // Later, we add IP addresses.
103  ipv4.SetBase("10.1.1.0", "255.255.255.0");
104  Ipv4InterfaceContainer iSrciRtr1 = ipv4.Assign(dSrcdRtr1);
105  ipv4.SetBase("10.1.2.0", "255.255.255.0");
106  Ipv4InterfaceContainer iSrciRtr2 = ipv4.Assign(dSrcdRtr2);
107  ipv4.SetBase("10.10.1.0", "255.255.255.0");
108  Ipv4InterfaceContainer iRtr1iDstRtr = ipv4.Assign(dRtr1dDstRtr);
109  ipv4.SetBase("10.10.2.0", "255.255.255.0");
110  Ipv4InterfaceContainer iRtr2iDstRtr = ipv4.Assign(dRtr2dDstRtr);
111  ipv4.SetBase("10.20.1.0", "255.255.255.0");
112  Ipv4InterfaceContainer iDstRtrDst = ipv4.Assign(dDstRtrdDst);
113 
114  Ptr<Ipv4> ipv4Src = nSrc->GetObject<Ipv4>();
115  Ptr<Ipv4> ipv4Rtr1 = nRtr1->GetObject<Ipv4>();
116  Ptr<Ipv4> ipv4Rtr2 = nRtr2->GetObject<Ipv4>();
117  Ptr<Ipv4> ipv4DstRtr = nDstRtr->GetObject<Ipv4>();
118  Ptr<Ipv4> ipv4Dst = nDst->GetObject<Ipv4>();
119 
120  Ipv4StaticRoutingHelper ipv4RoutingHelper;
121  Ptr<Ipv4StaticRouting> staticRoutingSrc = ipv4RoutingHelper.GetStaticRouting(ipv4Src);
122  Ptr<Ipv4StaticRouting> staticRoutingRtr1 = ipv4RoutingHelper.GetStaticRouting(ipv4Rtr1);
123  Ptr<Ipv4StaticRouting> staticRoutingRtr2 = ipv4RoutingHelper.GetStaticRouting(ipv4Rtr2);
124  Ptr<Ipv4StaticRouting> staticRoutingDstRtr = ipv4RoutingHelper.GetStaticRouting(ipv4DstRtr);
125  Ptr<Ipv4StaticRouting> staticRoutingDst = ipv4RoutingHelper.GetStaticRouting(ipv4Dst);
126 
127  // Create static routes from Src to Dst
128  staticRoutingRtr1->AddHostRouteTo(Ipv4Address("10.20.1.2"), Ipv4Address("10.10.1.2"), 2);
129  staticRoutingRtr2->AddHostRouteTo(Ipv4Address("10.20.1.2"), Ipv4Address("10.10.2.2"), 2);
130 
131  // Two routes to same destination - setting separate metrics.
132  // You can switch these to see how traffic gets diverted via different routes
133  staticRoutingSrc->AddHostRouteTo(Ipv4Address("10.20.1.2"), Ipv4Address("10.1.1.2"), 1, 5);
134  staticRoutingSrc->AddHostRouteTo(Ipv4Address("10.20.1.2"), Ipv4Address("10.1.2.2"), 2, 10);
135 
136  // Creating static routes from DST to Source pointing to Rtr1 VIA Rtr2(!)
137  staticRoutingDst->AddHostRouteTo(Ipv4Address("10.1.1.1"), Ipv4Address("10.20.1.1"), 1);
138  staticRoutingDstRtr->AddHostRouteTo(Ipv4Address("10.1.1.1"), Ipv4Address("10.10.2.1"), 2);
139  staticRoutingRtr2->AddHostRouteTo(Ipv4Address("10.1.1.1"), Ipv4Address("10.1.2.1"), 1);
140 
141  staticRoutingDst->AddHostRouteTo(Ipv4Address("10.1.2.1"), Ipv4Address("10.20.1.1"), 1);
142  staticRoutingDstRtr->AddHostRouteTo(Ipv4Address("10.1.2.1"), Ipv4Address("10.10.2.1"), 2);
143  staticRoutingRtr2->AddHostRouteTo(Ipv4Address("10.1.2.1"), Ipv4Address("10.1.2.1"), 1);
144 
145  // There are no apps that can utilize the Socket Option so doing the work directly..
146  // Taken from tcp-large-transfer example
147 
148  Ptr<Socket> srcSocket1 =
149  Socket::CreateSocket(nSrc, TypeId::LookupByName("ns3::TcpSocketFactory"));
150  Ptr<Socket> srcSocket2 =
151  Socket::CreateSocket(nSrc, TypeId::LookupByName("ns3::TcpSocketFactory"));
152  Ptr<Socket> srcSocket3 =
153  Socket::CreateSocket(nSrc, TypeId::LookupByName("ns3::TcpSocketFactory"));
154  Ptr<Socket> srcSocket4 =
155  Socket::CreateSocket(nSrc, TypeId::LookupByName("ns3::TcpSocketFactory"));
156 
157  uint16_t dstport = 12345;
158  Ipv4Address dstaddr("10.20.1.2");
159 
160  PacketSinkHelper sink("ns3::TcpSocketFactory",
162  ApplicationContainer apps = sink.Install(nDst);
163  apps.Start(Seconds(0.0));
164  apps.Stop(Seconds(10.0));
165 
166  AsciiTraceHelper ascii;
167  p2p.EnableAsciiAll(ascii.CreateFileStream("socket-bound-tcp-static-routing.tr"));
168  p2p.EnablePcapAll("socket-bound-tcp-static-routing");
169 
171  LogComponentEnable("SocketBoundTcpRoutingExample", LOG_LEVEL_INFO);
172 
173  // First packet as normal (goes via Rtr1)
174  Simulator::Schedule(Seconds(0.1), &StartFlow, srcSocket1, dstaddr, dstport);
175  // Second via Rtr1 explicitly
176  Simulator::Schedule(Seconds(1.0), &BindSock, srcSocket2, SrcToRtr1);
177  Simulator::Schedule(Seconds(1.1), &StartFlow, srcSocket2, dstaddr, dstport);
178  // Third via Rtr2 explicitly
179  Simulator::Schedule(Seconds(2.0), &BindSock, srcSocket3, SrcToRtr2);
180  Simulator::Schedule(Seconds(2.1), &StartFlow, srcSocket3, dstaddr, dstport);
181  // Fourth again as normal (goes via Rtr1)
182  Simulator::Schedule(Seconds(3.0), &BindSock, srcSocket4, Ptr<NetDevice>(nullptr));
183  Simulator::Schedule(Seconds(3.1), &StartFlow, srcSocket4, dstaddr, dstport);
184  // If you uncomment what's below, it results in ASSERT failing since you can't
185  // bind to a socket not existing on a node
186  // Simulator::Schedule(Seconds(4.0),&BindSock, srcSocket, dDstRtrdDst.Get(0));
187  Simulator::Run();
189 
190  return 0;
191 }
192 
193 void
195 {
196  sock->BindToNetDevice(netdev);
197 }
198 
199 void
200 StartFlow(Ptr<Socket> localSocket, Ipv4Address servAddress, uint16_t servPort)
201 {
202  NS_LOG_INFO("Starting flow at time " << Simulator::Now().GetSeconds());
203  currentTxBytes = 0;
204  localSocket->Bind();
205  localSocket->Connect(InetSocketAddress(servAddress, servPort)); // connect
206 
207  // tell the tcp implementation to call WriteUntilBufferFull again
208  // if we blocked and new tx buffer space becomes available
210  WriteUntilBufferFull(localSocket, localSocket->GetTxAvailable());
211 }
212 
213 void
214 WriteUntilBufferFull(Ptr<Socket> localSocket, uint32_t txSpace)
215 {
216  while (currentTxBytes < totalTxBytes && localSocket->GetTxAvailable() > 0)
217  {
218  uint32_t left = totalTxBytes - currentTxBytes;
219  uint32_t dataOffset = currentTxBytes % writeSize;
220  uint32_t toWrite = writeSize - dataOffset;
221  toWrite = std::min(toWrite, left);
222  toWrite = std::min(toWrite, localSocket->GetTxAvailable());
223  int amountSent = localSocket->Send(&data[dataOffset], toWrite, 0);
224  if (amountSent < 0)
225  {
226  // we will be called again when new tx space becomes available.
227  return;
228  }
229  currentTxBytes += amountSent;
230  }
231  localSocket->Close();
232 }
#define min(a, b)
Definition: 80211b.c:41
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.
Manage ASCII trace files for device models.
Definition: trace-helper.h:174
Ptr< OutputStreamWrapper > CreateFileStream(std::string filename, std::ios::openmode filemode=std::ios::out)
Create and initialize an output stream object we'll use to write the traced bits.
Parse command-line arguments.
Definition: command-line.h:232
an Inet address class
aggregate IP/TCP/UDP functionality to existing Nodes.
A helper class to make life easier while doing simple IPv4 address assignment in scripts.
Ipv4 addresses are stored in host order in this class.
Definition: ipv4-address.h:42
static Ipv4Address GetAny()
Access to the IPv4 forwarding table, interfaces, and configuration.
Definition: ipv4.h:80
holds a vector of std::pair of Ptr<Ipv4> and interface index.
Helper class that adds ns3::Ipv4StaticRouting objects.
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.
Ptr< T > GetObject() const
Get a pointer to the requested aggregated Object.
Definition: object.h:471
A helper to make it easier to instantiate an ns3::PacketSinkApplication on a set of nodes.
Build a set of PointToPointNetDevice objects.
static EventId Schedule(const Time &delay, FUNC f, Ts &&... args)
Schedule an event to expire after delay.
Definition: simulator.h:571
static void Destroy()
Execute the events scheduled with ScheduleDestroy().
Definition: simulator.cc:142
static Time Now()
Return the current simulation virtual time.
Definition: simulator.cc:208
static void Run()
Run the simulation.
Definition: simulator.cc:178
virtual int Send(Ptr< Packet > p, uint32_t flags)=0
Send data (or dummy data) to the remote host.
void SetSendCallback(Callback< void, Ptr< Socket >, uint32_t > sendCb)
Notify application when space in transmit buffer is added.
Definition: socket.cc:121
virtual int Connect(const Address &address)=0
Initiate a connection to a remote host.
virtual void BindToNetDevice(Ptr< NetDevice > netdevice)
Bind a socket to specific device.
Definition: socket.cc:327
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:72
virtual int Close()=0
Close a socket.
virtual int Bind(const Address &address)=0
Allocate a local endpoint for this socket.
virtual uint32_t GetTxAvailable() const =0
Returns the number of bytes which can be sent in a single call to Send.
Hold variables of type string.
Definition: string.h:56
static TypeId LookupByName(std::string name)
Get a TypeId by name.
Definition: type-id.cc:835
uint16_t port
Definition: dsdv-manet.cc:44
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition: log.h:202
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition: log.h:275
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition: nstime.h:1326
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:302
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:704
@ LOG_PREFIX_TIME
Prefix all trace prints with simulation time.
Definition: log.h:119
@ LOG_LEVEL_INFO
LOG_INFO and above.
Definition: log.h:104
void LogComponentEnableAll(LogLevel level)
Enable the logging output for all registered log components.
Definition: log.cc:320
cmd
Definition: second.py:40
static const uint32_t totalTxBytes
void srcSocketRecv(Ptr< Socket > socket)
void dstSocketRecv(Ptr< Socket > socket)
void SendStuff(Ptr< Socket > sock, Ipv4Address dstaddr, uint16_t port)
static const uint32_t writeSize
void WriteUntilBufferFull(Ptr< Socket >, uint32_t)
static uint32_t currentTxBytes
uint8_t data[writeSize]
void BindSock(Ptr< Socket > sock, Ptr< NetDevice > netdev)
void StartFlow(Ptr< Socket >, Ipv4Address, uint16_t)
Ptr< PacketSink > sink
Pointer to the packet sink application.
Definition: wifi-tcp.cc:55