A Discrete-Event Network Simulator
API
packet-sink.cc
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright 2007 University of Washington
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: Tom Henderson (tomhend@u.washington.edu)
19  */
20 #include "ns3/address.h"
21 #include "ns3/address-utils.h"
22 #include "ns3/log.h"
23 #include "ns3/inet-socket-address.h"
24 #include "ns3/inet6-socket-address.h"
25 #include "ns3/node.h"
26 #include "ns3/socket.h"
27 #include "ns3/udp-socket.h"
28 #include "ns3/simulator.h"
29 #include "ns3/socket-factory.h"
30 #include "ns3/packet.h"
31 #include "ns3/trace-source-accessor.h"
32 #include "ns3/udp-socket-factory.h"
33 #include "packet-sink.h"
34 #include "ns3/boolean.h"
35 
36 namespace ns3 {
37 
38 NS_LOG_COMPONENT_DEFINE ("PacketSink");
39 
40 NS_OBJECT_ENSURE_REGISTERED (PacketSink);
41 
42 TypeId
44 {
45  static TypeId tid = TypeId ("ns3::PacketSink")
47  .SetGroupName("Applications")
48  .AddConstructor<PacketSink> ()
49  .AddAttribute ("Local",
50  "The Address on which to Bind the rx socket.",
51  AddressValue (),
54  .AddAttribute ("Protocol",
55  "The type id of the protocol to use for the rx socket.",
59  .AddAttribute ("EnableSeqTsSizeHeader",
60  "Enable optional header tracing of SeqTsSizeHeader",
61  BooleanValue (false),
64  .AddTraceSource ("Rx",
65  "A packet has been received",
67  "ns3::Packet::AddressTracedCallback")
68  .AddTraceSource ("RxWithAddresses", "A packet has been received",
70  "ns3::Packet::TwoAddressTracedCallback")
71  .AddTraceSource ("RxWithSeqTsSize",
72  "A packet with SeqTsSize header has been received",
74  "ns3::PacketSink::SeqTsSizeCallback")
75  ;
76  return tid;
77 }
78 
80 {
81  NS_LOG_FUNCTION (this);
82  m_socket = 0;
83  m_totalRx = 0;
84 }
85 
87 {
88  NS_LOG_FUNCTION (this);
89 }
90 
91 uint64_t PacketSink::GetTotalRx () const
92 {
93  NS_LOG_FUNCTION (this);
94  return m_totalRx;
95 }
96 
99 {
100  NS_LOG_FUNCTION (this);
101  return m_socket;
102 }
103 
104 std::list<Ptr<Socket> >
106 {
107  NS_LOG_FUNCTION (this);
108  return m_socketList;
109 }
110 
112 {
113  NS_LOG_FUNCTION (this);
114  m_socket = 0;
115  m_socketList.clear ();
116 
117  // chain up
119 }
120 
121 
122 // Application Methods
123 void PacketSink::StartApplication () // Called at time specified by Start
124 {
125  NS_LOG_FUNCTION (this);
126  // Create the socket if not already
127  if (!m_socket)
128  {
130  if (m_socket->Bind (m_local) == -1)
131  {
132  NS_FATAL_ERROR ("Failed to bind socket");
133  }
134  m_socket->Listen ();
137  {
138  Ptr<UdpSocket> udpSocket = DynamicCast<UdpSocket> (m_socket);
139  if (udpSocket)
140  {
141  // equivalent to setsockopt (MCAST_JOIN_GROUP)
142  udpSocket->MulticastJoinGroup (0, m_local);
143  }
144  else
145  {
146  NS_FATAL_ERROR ("Error: joining multicast on a non-UDP socket");
147  }
148  }
149  }
150 
153  MakeNullCallback<bool, Ptr<Socket>, const Address &> (),
158 }
159 
160 void PacketSink::StopApplication () // Called at time specified by Stop
161 {
162  NS_LOG_FUNCTION (this);
163  while(!m_socketList.empty ()) //these are accepted sockets, close them
164  {
165  Ptr<Socket> acceptedSocket = m_socketList.front ();
166  m_socketList.pop_front ();
167  acceptedSocket->Close ();
168  }
169  if (m_socket)
170  {
171  m_socket->Close ();
173  }
174 }
175 
177 {
178  NS_LOG_FUNCTION (this << socket);
179  Ptr<Packet> packet;
180  Address from;
181  Address localAddress;
182  while ((packet = socket->RecvFrom (from)))
183  {
184  if (packet->GetSize () == 0)
185  { //EOF
186  break;
187  }
188  m_totalRx += packet->GetSize ();
190  {
191  NS_LOG_INFO ("At time " << Simulator::Now ().As (Time::S)
192  << " packet sink received "
193  << packet->GetSize () << " bytes from "
195  << " port " << InetSocketAddress::ConvertFrom (from).GetPort ()
196  << " total Rx " << m_totalRx << " bytes");
197  }
198  else if (Inet6SocketAddress::IsMatchingType (from))
199  {
200  NS_LOG_INFO ("At time " << Simulator::Now ().As (Time::S)
201  << " packet sink received "
202  << packet->GetSize () << " bytes from "
204  << " port " << Inet6SocketAddress::ConvertFrom (from).GetPort ()
205  << " total Rx " << m_totalRx << " bytes");
206  }
207  socket->GetSockName (localAddress);
208  m_rxTrace (packet, from);
209  m_rxTraceWithAddresses (packet, from, localAddress);
210 
212  {
213  PacketReceived (packet, from, localAddress);
214  }
215  }
216 }
217 
218 void
220  const Address &localAddress)
221 {
222  SeqTsSizeHeader header;
223  Ptr<Packet> buffer;
224 
225  auto itBuffer = m_buffer.find (from);
226  if (itBuffer == m_buffer.end ())
227  {
228  itBuffer = m_buffer.insert (std::make_pair (from, Create<Packet> (0))).first;
229  }
230 
231  buffer = itBuffer->second;
232  buffer->AddAtEnd (p);
233  buffer->PeekHeader (header);
234 
235  NS_ABORT_IF (header.GetSize () == 0);
236 
237  while (buffer->GetSize () >= header.GetSize ())
238  {
239  NS_LOG_DEBUG ("Removing packet of size " << header.GetSize () << " from buffer of size " << buffer->GetSize ());
240  Ptr<Packet> complete = buffer->CreateFragment (0, static_cast<uint32_t> (header.GetSize ()));
241  buffer->RemoveAtStart (static_cast<uint32_t> (header.GetSize ()));
242 
243  complete->RemoveHeader (header);
244 
245  m_rxTraceWithSeqTsSize (complete, from, localAddress, header);
246 
247  if (buffer->GetSize () > header.GetSerializedSize ())
248  {
249  buffer->PeekHeader (header);
250  }
251  else
252  {
253  break;
254  }
255  }
256 }
257 
259 {
260  NS_LOG_FUNCTION (this << socket);
261 }
262 
264 {
265  NS_LOG_FUNCTION (this << socket);
266 }
267 
269 {
270  NS_LOG_FUNCTION (this << s << from);
272  m_socketList.push_back (s);
273 }
274 
275 } // Namespace ns3
a polymophic address class
Definition: address.h:91
AttributeValue implementation for Address.
Definition: address.h:278
The base class for all ns3 applications.
Definition: application.h:61
virtual void DoDispose(void)
Destructor implementation.
Definition: application.cc:83
Ptr< Node > GetNode() const
Definition: application.cc:104
AttributeValue implementation for Boolean.
Definition: boolean.h:37
static Inet6SocketAddress ConvertFrom(const Address &addr)
Convert the address to a InetSocketAddress.
static bool IsMatchingType(const Address &addr)
If the address match.
Ipv6Address GetIpv6(void) const
Get the IPv6 address.
uint16_t GetPort(void) const
Get the port.
uint16_t GetPort(void) const
Ipv4Address GetIpv4(void) const
static bool IsMatchingType(const Address &address)
static InetSocketAddress ConvertFrom(const Address &address)
Returns an InetSocketAddress which corresponds to the input Address.
uint32_t RemoveHeader(Header &header)
Deserialize and remove the header from the internal buffer.
Definition: packet.cc:280
void AddAtEnd(Ptr< const Packet > packet)
Concatenate the input packet at the end of the current packet.
Definition: packet.cc:335
void RemoveAtStart(uint32_t size)
Remove size bytes from the start of the current packet.
Definition: packet.cc:362
uint32_t PeekHeader(Header &header) const
Deserialize but does not remove the header from the internal buffer.
Definition: packet.cc:290
Ptr< Packet > CreateFragment(uint32_t start, uint32_t length) const
Create a new packet which contains a fragment of the original packet.
Definition: packet.cc:227
uint32_t GetSize(void) const
Returns the the size in bytes of the packet (including the zero-filled initial payload).
Definition: packet.h:852
Receive and consume traffic generated to an IP address and port.
Definition: packet-sink.h:72
virtual void DoDispose(void)
Destructor implementation.
Definition: packet-sink.cc:111
std::unordered_map< Address, Ptr< Packet >, AddressHash > m_buffer
Buffer for received packets.
Definition: packet-sink.h:172
Ptr< Socket > GetListeningSocket(void) const
Definition: packet-sink.cc:98
TypeId m_tid
Protocol TypeId.
Definition: packet-sink.h:181
static TypeId GetTypeId(void)
Get the type ID.
Definition: packet-sink.cc:43
Address m_local
Local address to bind to.
Definition: packet-sink.h:179
std::list< Ptr< Socket > > GetAcceptedSockets(void) const
Definition: packet-sink.cc:105
virtual void StartApplication(void)
Application specific startup code.
Definition: packet-sink.cc:123
std::list< Ptr< Socket > > m_socketList
the accepted sockets
Definition: packet-sink.h:177
virtual void StopApplication(void)
Application specific shutdown code.
Definition: packet-sink.cc:160
void HandleRead(Ptr< Socket > socket)
Handle a packet received by the application.
Definition: packet-sink.cc:176
uint64_t GetTotalRx() const
Definition: packet-sink.cc:91
void HandleAccept(Ptr< Socket > socket, const Address &from)
Handle an incoming connection.
Definition: packet-sink.cc:268
void HandlePeerError(Ptr< Socket > socket)
Handle an connection error.
Definition: packet-sink.cc:263
TracedCallback< Ptr< const Packet >, const Address & > m_rxTrace
Traced Callback: received packets, source address.
Definition: packet-sink.h:186
TracedCallback< Ptr< const Packet >, const Address &, const Address & > m_rxTraceWithAddresses
Callback for tracing the packet Rx events, includes source and destination addresses.
Definition: packet-sink.h:188
uint64_t m_totalRx
Total bytes received.
Definition: packet-sink.h:180
bool m_enableSeqTsSizeHeader
Enable or disable the export of SeqTsSize header.
Definition: packet-sink.h:183
TracedCallback< Ptr< const Packet >, const Address &, const Address &, const SeqTsSizeHeader & > m_rxTraceWithSeqTsSize
Callbacks for tracing the packet Rx events, includes source, destination addresses,...
Definition: packet-sink.h:190
void HandlePeerClose(Ptr< Socket > socket)
Handle an connection close.
Definition: packet-sink.cc:258
Ptr< Socket > m_socket
Listening socket.
Definition: packet-sink.h:176
void PacketReceived(const Ptr< Packet > &p, const Address &from, const Address &localAddress)
Packet received: assemble byte stream to extract SeqTsSizeHeader.
Definition: packet-sink.cc:219
virtual ~PacketSink()
Definition: packet-sink.cc:86
Header with a sequence, a timestamp, and a "size" attribute.
virtual uint32_t GetSerializedSize(void) const override
uint64_t GetSize(void) const
Get the size information that the header is carrying.
static Time Now(void)
Return the current simulation virtual time.
Definition: simulator.cc:195
void SetAcceptCallback(Callback< bool, Ptr< Socket >, const Address & > connectionRequest, Callback< void, Ptr< Socket >, const Address & > newConnectionCreated)
Accept connection requests from remote hosts.
Definition: socket.cc:104
virtual int Listen(void)=0
Listen for incoming connections.
virtual int ShutdownSend(void)=0
virtual int GetSockName(Address &address) const =0
Get socket address.
virtual int Close(void)=0
Close a socket.
void SetCloseCallbacks(Callback< void, Ptr< Socket > > normalClose, Callback< void, Ptr< Socket > > errorClose)
Detect socket recv() events such as graceful shutdown or error.
Definition: socket.cc:94
void SetRecvCallback(Callback< void, Ptr< Socket > > receivedData)
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
virtual int Bind(const Address &address)=0
Allocate a local endpoint for this socket.
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.
@ S
second
Definition: nstime.h:115
a unique identifier for an interface.
Definition: type-id.h:59
TypeId SetParent(TypeId tid)
Set the parent TypeId.
Definition: type-id.cc:923
AttributeValue implementation for TypeId.
Definition: type-id.h:595
static TypeId GetTypeId(void)
Get the type ID.
Ptr< const AttributeAccessor > MakeAddressAccessor(T1 a1)
Create an AttributeAccessor for a class data member, or a lone class get functor or set method.
Definition: address.h:278
Ptr< const AttributeChecker > MakeAddressChecker(void)
Definition: address.cc:172
Ptr< const AttributeChecker > MakeBooleanChecker(void)
Definition: boolean.cc:121
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:85
Ptr< const AttributeAccessor > MakeTypeIdAccessor(T1 a1)
Create an AttributeAccessor for a class data member, or a lone class get functor or set method.
Definition: type-id.h:595
Ptr< const AttributeChecker > MakeTypeIdChecker(void)
Definition: type-id.cc:1227
Callback< R, Ts... > MakeNullCallback(void)
Definition: callback.h:1682
#define NS_FATAL_ERROR(msg)
Report a fatal error with a message and terminate.
Definition: fatal-error.h:165
#define NS_ABORT_IF(cond)
Abnormal program termination if a condition is true.
Definition: abort.h:77
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition: log.h:205
#define NS_LOG_DEBUG(msg)
Use NS_LOG to output a message of level LOG_DEBUG.
Definition: log.h:273
#define NS_LOG_FUNCTION(parameters)
If log level LOG_FUNCTION is enabled, this macro will output all input parameters separated by ",...
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition: log.h:281
#define NS_OBJECT_ENSURE_REGISTERED(type)
Register an Object subclass with the TypeId system.
Definition: object-base.h:45
Ptr< const TraceSourceAccessor > MakeTraceSourceAccessor(T a)
Create a TraceSourceAccessor which will control access to the underlying trace source.
bool IsMulticast(const Address &ad)
Address family-independent test for a multicast address.
Every class exported by the ns3 library is enclosed in the ns3 namespace.
Callback< R, Ts... > MakeCallback(R(T::*memPtr)(Ts...), OBJ objPtr)
Build Callbacks for class method members which take varying numbers of arguments and potentially retu...
Definition: callback.h:1642