A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
packet-sink.cc
Go to the documentation of this file.
1/*
2 * Copyright 2007 University of Washington
3 *
4 * SPDX-License-Identifier: GPL-2.0-only
5 *
6 * Author: Tom Henderson (tomhend@u.washington.edu)
7 */
8
9#include "packet-sink.h"
10
11#include "ns3/address-utils.h"
12#include "ns3/boolean.h"
13#include "ns3/inet-socket-address.h"
14#include "ns3/inet6-socket-address.h"
15#include "ns3/ipv4-packet-info-tag.h"
16#include "ns3/ipv6-packet-info-tag.h"
17#include "ns3/log.h"
18#include "ns3/node.h"
19#include "ns3/packet.h"
20#include "ns3/simulator.h"
21#include "ns3/socket-factory.h"
22#include "ns3/socket.h"
23#include "ns3/trace-source-accessor.h"
24#include "ns3/udp-socket-factory.h"
25#include "ns3/udp-socket.h"
26#include "ns3/uinteger.h"
27
28namespace ns3
29{
30
31NS_LOG_COMPONENT_DEFINE("PacketSink");
32
34
37{
38 static TypeId tid =
39 TypeId("ns3::PacketSink")
41 .SetGroupName("Applications")
42 .AddConstructor<PacketSink>()
43 .AddAttribute("Protocol",
44 "The type id of the protocol to use for the rx socket.",
48 .AddAttribute("EnableSeqTsSizeHeader",
49 "Enable optional header tracing of SeqTsSizeHeader",
50 BooleanValue(false),
53 .AddAttribute("Tos",
54 "The Type of Service used to send IPv4 packets. "
55 "All 8 bits of the TOS byte are set (including ECN bits).",
59 .AddTraceSource("RxWithAddresses",
60 "A packet has been received",
62 "ns3::Packet::TwoAddressTracedCallback")
63 .AddTraceSource("RxWithSeqTsSize",
64 "A packet with SeqTsSize header has been received",
66 "ns3::PacketSink::SeqTsSizeCallback");
67 return tid;
68}
69
74
79
80uint64_t
82{
83 NS_LOG_FUNCTION(this);
84 return m_totalRx;
85}
86
89{
90 NS_LOG_FUNCTION(this);
91 return m_socket;
92}
93
94std::list<Ptr<Socket>>
96{
97 NS_LOG_FUNCTION(this);
98 return m_socketList;
99}
100
101void
103{
104 NS_LOG_FUNCTION(this);
105 m_socketList.clear();
106
107 // chain up
109}
110
111// Application Methods
112void
113PacketSink::DoStartApplication() // Called at time specified by Start
114{
115 NS_LOG_FUNCTION(this);
116
117 auto local = m_local;
118 if (local.IsInvalid())
119 {
121 NS_LOG_INFO(this << " Binding on port " << m_port << " / " << local << ".");
122 }
123 else if (InetSocketAddress::IsMatchingType(local))
124 {
126 const auto ipv4 = InetSocketAddress::ConvertFrom(local).GetIpv4();
127 NS_LOG_INFO(this << " Binding on " << ipv4 << " port " << m_port << " / " << local << ".");
128 }
130 {
132 const auto ipv6 = Inet6SocketAddress::ConvertFrom(local).GetIpv6();
133 NS_LOG_INFO(this << " Binding on " << ipv6 << " port " << m_port << " / " << local << ".");
134 }
135 if (m_socket->Bind(local) == -1)
136 {
137 NS_FATAL_ERROR("Failed to bind socket");
138 }
139 m_socket->Listen();
140 m_socket->ShutdownSend();
141 if (addressUtils::IsMulticast(local))
142 {
143 if (auto udpSocket = DynamicCast<UdpSocket>(m_socket))
144 {
145 // equivalent to setsockopt (MCAST_JOIN_GROUP)
146 udpSocket->MulticastJoinGroup(0, local);
147 }
148 else
149 {
150 NS_FATAL_ERROR("Error: joining multicast on a non-UDP socket");
151 }
152 }
153 m_socket->SetRecvCallback(MakeCallback(&PacketSink::HandleRead, this));
154 m_socket->SetRecvPktInfo(true);
155 m_socket->SetAcceptCallback(MakeNullCallback<bool, Ptr<Socket>, const Address&>(),
157 m_socket->SetCloseCallbacks(MakeCallback(&PacketSink::HandlePeerClose, this),
159
160 if (m_local.IsInvalid())
161 {
163 if (m_socket6->Bind(local) == -1)
164 {
165 NS_FATAL_ERROR("Failed to bind socket");
166 }
167 m_socket6->Listen();
168 m_socket6->ShutdownSend();
169 if (addressUtils::IsMulticast(local))
170 {
171 if (auto udpSocket = DynamicCast<UdpSocket>(m_socket6))
172 {
173 // equivalent to setsockopt (MCAST_JOIN_GROUP)
174 udpSocket->MulticastJoinGroup(0, local);
175 }
176 else
177 {
178 NS_FATAL_ERROR("Error: joining multicast on a non-UDP socket");
179 }
180 }
181 m_socket6->SetRecvCallback(MakeCallback(&PacketSink::HandleRead, this));
182 m_socket6->SetRecvPktInfo(true);
183 m_socket6->SetAcceptCallback(MakeNullCallback<bool, Ptr<Socket>, const Address&>(),
185 m_socket6->SetCloseCallbacks(MakeCallback(&PacketSink::HandlePeerClose, this),
187 }
188}
189
190void
191PacketSink::DoStopApplication() // Called at time specified by Stop
192{
193 NS_LOG_FUNCTION(this);
194 while (!m_socketList.empty()) // these are accepted sockets, close them
195 {
196 auto acceptedSocket = m_socketList.front();
197 m_socketList.pop_front();
198 acceptedSocket->Close();
199 }
200}
201
202void
204{
205 NS_LOG_FUNCTION(this << socket);
206 Address from;
207 while (auto packet = socket->RecvFrom(from))
208 {
209 if (packet->GetSize() == 0)
210 { // EOF
211 break;
212 }
213 m_totalRx += packet->GetSize();
215 {
216 NS_LOG_INFO("At time " << Simulator::Now().As(Time::S) << " packet sink received "
217 << packet->GetSize() << " bytes from "
218 << InetSocketAddress::ConvertFrom(from).GetIpv4() << " port "
219 << InetSocketAddress::ConvertFrom(from).GetPort() << " total Rx "
220 << m_totalRx << " bytes");
221 }
223 {
224 NS_LOG_INFO("At time " << Simulator::Now().As(Time::S) << " packet sink received "
225 << packet->GetSize() << " bytes from "
226 << Inet6SocketAddress::ConvertFrom(from).GetIpv6() << " port "
227 << Inet6SocketAddress::ConvertFrom(from).GetPort()
228 << " total Rx " << m_totalRx << " bytes");
229 }
230
231 if (!m_rxTrace.IsEmpty() || !m_rxTraceWithoutAddress.IsEmpty() ||
232 !m_rxTraceWithAddresses.IsEmpty() ||
234 {
235 Address localAddress;
236 Ipv4PacketInfoTag interfaceInfo;
237 Ipv6PacketInfoTag interface6Info;
238 if (packet->RemovePacketTag(interfaceInfo))
239 {
240 localAddress = InetSocketAddress(interfaceInfo.GetAddress(), m_port);
241 }
242 else if (packet->RemovePacketTag(interface6Info))
243 {
244 localAddress = Inet6SocketAddress(interface6Info.GetAddress(), m_port);
245 }
246 else
247 {
248 socket->GetSockName(localAddress);
249 }
251 m_rxTrace(packet, from);
252 m_rxTraceWithAddresses(packet, from, localAddress);
253
255 {
256 PacketReceived(packet, from, localAddress);
257 }
258 }
259 }
260}
261
262void
263PacketSink::PacketReceived(const Ptr<Packet>& p, const Address& from, const Address& localAddress)
264{
265 auto itBuffer = m_buffer.find(from);
266 if (itBuffer == m_buffer.end())
267 {
268 itBuffer = m_buffer.emplace(from, Create<Packet>(0)).first;
269 }
270
271 auto buffer = itBuffer->second;
272 buffer->AddAtEnd(p);
273
274 SeqTsSizeHeader header;
275 buffer->PeekHeader(header);
276
277 NS_ABORT_IF(header.GetSize() == 0);
278
279 while (buffer->GetSize() >= header.GetSize())
280 {
281 NS_LOG_DEBUG("Removing packet of size " << header.GetSize() << " from buffer of size "
282 << buffer->GetSize());
283 auto complete = buffer->CreateFragment(0, static_cast<uint32_t>(header.GetSize()));
284 buffer->RemoveAtStart(static_cast<uint32_t>(header.GetSize()));
285
286 complete->RemoveHeader(header);
287
288 m_rxTraceWithSeqTsSize(complete, from, localAddress, header);
289
290 if (buffer->GetSize() > header.GetSerializedSize())
291 {
292 buffer->PeekHeader(header);
293 }
294 else
295 {
296 break;
297 }
298 }
299}
300
301void
303{
304 NS_LOG_FUNCTION(this << socket);
305}
306
307void
309{
310 NS_LOG_FUNCTION(this << socket);
311}
312
313void
315{
316 NS_LOG_FUNCTION(this << s << from);
317 s->SetRecvCallback(MakeCallback(&PacketSink::HandleRead, this));
318 if (m_tos)
319 {
320 s->SetIpTos(m_tos);
321 }
322 m_socketList.push_back(s);
323}
324
325} // Namespace ns3
a polymophic address class
Definition address.h:114
An Inet6 address class.
static Inet6SocketAddress ConvertFrom(const Address &addr)
Convert the address to a InetSocketAddress.
uint16_t GetPort() const
Get the port.
static bool IsMatchingType(const Address &addr)
If the address match.
Ipv6Address GetIpv6() const
Get the IPv6 address.
an Inet address class
static bool IsMatchingType(const Address &address)
Ipv4Address GetIpv4() const
static InetSocketAddress ConvertFrom(const Address &address)
Returns an InetSocketAddress which corresponds to the input Address.
static Ipv4Address GetAny()
This class implements Linux struct pktinfo in order to deliver ancillary information to the socket in...
Ipv4Address GetAddress() const
Get the tag's address.
static Ipv6Address GetAny()
Get the "any" (::) Ipv6Address.
This class implements a tag that carries socket ancillary data to the socket interface.
Ipv6Address GetAddress() const
Get the tag's address.
Receive and consume traffic generated to an IP address and port.
Definition packet-sink.h:61
static TypeId GetTypeId()
Get the type ID.
std::unordered_map< Address, Ptr< Packet >, AddressHash > m_buffer
Buffer for received packets.
TracedCallback< Ptr< const Packet >, const Address &, const Address & > m_rxTraceWithAddresses
Callback for tracing the packet Rx events, includes source and destination addresses.
uint8_t m_tos
Type of Service for outbound packets.
void DoStartApplication() override
Application specific startup code for child subclasses.
Ptr< Socket > GetListeningSocket() const
std::list< Ptr< Socket > > m_socketList
the accepted sockets
void HandleRead(Ptr< Socket > socket)
Handle a packet received by the application.
uint64_t GetTotalRx() const
void HandleAccept(Ptr< Socket > socket, const Address &from)
Handle an incoming connection.
void DoStopApplication() override
Application specific shutdown code for child subclasses.
void HandlePeerError(Ptr< Socket > socket)
Handle an connection error.
TracedCallback< Ptr< const Packet >, const Address &, const Address &, const SeqTsSizeHeader & > m_rxTraceWithSeqTsSize
Callbacks for tracing the packet Rx events, includes source, destination addresses,...
uint64_t m_totalRx
Total bytes received.
~PacketSink() override
void DoDispose() override
Destructor implementation.
bool m_enableSeqTsSizeHeader
Enable or disable the export of SeqTsSize header.
std::list< Ptr< Socket > > GetAcceptedSockets() const
void HandlePeerClose(Ptr< Socket > socket)
Handle an connection close.
void PacketReceived(const Ptr< Packet > &p, const Address &from, const Address &localAddress)
Packet received: assemble byte stream to extract SeqTsSizeHeader.
Smart pointer class similar to boost::intrusive_ptr.
Definition ptr.h:70
Header with a sequence, a timestamp, and a "size" attribute.
uint32_t GetSerializedSize() const override
uint64_t GetSize() const
Get the size information that the header is carrying.
static Time Now()
Return the current simulation virtual time.
Definition simulator.cc:191
ns3::TracedCallback< Ptr< const Packet > > m_rxTraceWithoutAddress
Callbacks for tracing the packet Rx events.
Ptr< Socket > m_socket6
IPv6 Socket (used if only port is specified).
void DoDispose() override
Destructor implementation.
TypeId m_protocolTid
Protocol TypeId value.
SinkApplication(uint16_t defaultPort=0)
Constructor.
Address m_local
Local address to bind to (address and port).
Ptr< Socket > m_socket
Socket (IPv4 or IPv6, depending on local address).
uint32_t m_port
Local port to bind to.
TracedCallback< Ptr< const Packet >, const Address & > m_rxTrace
Traced Callback: received packets, source address.
@ S
second
Definition nstime.h:106
a unique identifier for an interface.
Definition type-id.h:50
TypeId SetParent(TypeId tid)
Set the parent TypeId.
Definition type-id.cc:1003
static TypeId GetTypeId()
Get the type ID.
Hold an unsigned integer type.
Definition uinteger.h:34
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:690
Callback< R, Args... > MakeNullCallback()
Build null Callbacks which take no arguments, for varying number of template arguments,...
Definition callback.h:734
#define NS_FATAL_ERROR(msg)
Report a fatal error with a message and terminate.
#define NS_ABORT_IF(cond)
Abnormal program termination if a condition is true.
Definition abort.h:66
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition log.h:201
#define NS_LOG_DEBUG(msg)
Use NS_LOG to output a message of level LOG_DEBUG.
Definition log.h:267
#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:274
#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:492
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.
Ptr< const AttributeChecker > MakeBooleanChecker()
Definition boolean.cc:113
Ptr< const AttributeChecker > MakeUintegerChecker()
Definition uinteger.h:85
Ptr< const AttributeAccessor > MakeUintegerAccessor(T1 a1)
Definition uinteger.h:35
Ptr< T1 > DynamicCast(const Ptr< T2 > &p)
Cast a Ptr.
Definition ptr.h:643
Ptr< const AttributeChecker > MakeTypeIdChecker()
Definition type-id.cc:1359
Ptr< const AttributeAccessor > MakeBooleanAccessor(T1 a1)
Definition boolean.h:70
Ptr< const AttributeAccessor > MakeTypeIdAccessor(T1 a1)
Definition type-id.h:666