A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
udp-client.cc
Go to the documentation of this file.
1/*
2 * Copyright (c) 2007,2008,2009 INRIA, UDCAST
3 *
4 * SPDX-License-Identifier: GPL-2.0-only
5 *
6 * Author: Amine Ismail <amine.ismail@sophia.inria.fr>
7 * <amine.ismail@udcast.com>
8 */
9
10#include "udp-client.h"
11
12#include "seq-ts-header.h"
13
14#include "ns3/address-utils.h"
15#include "ns3/log.h"
16#include "ns3/nstime.h"
17#include "ns3/packet.h"
18#include "ns3/simulator.h"
19#include "ns3/socket-factory.h"
20#include "ns3/socket.h"
21#include "ns3/uinteger.h"
22
23#include <cstdio>
24#include <cstdlib>
25
26namespace ns3
27{
28
29NS_LOG_COMPONENT_DEFINE("UdpClient");
30
32
33TypeId
35{
36 static TypeId tid =
37 TypeId("ns3::UdpClient")
39 .SetGroupName("Applications")
40 .AddConstructor<UdpClient>()
41 .AddAttribute(
42 "MaxPackets",
43 "The maximum number of packets the application will send (zero means infinite)",
44 UintegerValue(100),
47 .AddAttribute("Interval",
48 "The time to wait between packets",
52 // NS_DEPRECATED_3_44
53 .AddAttribute(
54 "RemoteAddress",
55 "The destination Address of the outbound packets",
58 // this is needed to indicate which version of the function overload to use
59 static_cast<void (UdpClient::*)(const Address&)>(&UdpClient::SetRemote),
63 "Replaced by Remote in ns-3.44.")
64 // NS_DEPRECATED_3_44
65 .AddAttribute("RemotePort",
66 "The destination port of the outbound packets",
71 "Replaced by Remote in ns-3.44.")
72 .AddAttribute("PacketSize",
73 "Size of packets generated. The minimum packet size is 12 bytes which is "
74 "the size of the header carrying the sequence number and the time stamp.",
75 UintegerValue(1024),
78 .AddTraceSource("Tx",
79 "A new packet is created and sent",
81 "ns3::Packet::TracedCallback")
82 .AddTraceSource("TxWithAddresses",
83 "A new packet is created and sent",
85 "ns3::Packet::TwoAddressTracedCallback");
86 return tid;
87}
88
90 : m_sent{0},
91 m_totalTx{0},
92 m_socket{nullptr},
93 m_peerPort{},
94 m_sendEvent{}
95{
96 NS_LOG_FUNCTION(this);
97}
98
103
104void
106{
107 NS_LOG_FUNCTION(this << ip << port);
108 SetRemote(ip);
109 SetPort(port);
110}
111
112void
114{
115 NS_LOG_FUNCTION(this << addr);
116 if (!addr.IsInvalid())
117 {
118 m_peer = addr;
119 if (m_peerPort)
120 {
122 }
123 }
124}
125
128{
129 return m_peer;
130}
131
132void
134{
135 NS_LOG_FUNCTION(this << port);
136 if (m_peer.IsInvalid())
137 {
138 // save for later
140 return;
141 }
143 {
145 }
146}
147
148uint16_t
165
166void
168{
169 NS_LOG_FUNCTION(this);
170
171 if (!m_socket)
172 {
173 auto tid = TypeId::LookupByName("ns3::UdpSocketFactory");
175 NS_ABORT_MSG_IF(m_peer.IsInvalid(), "Remote address not properly set");
176 if (!m_local.IsInvalid())
177 {
182 "Incompatible peer and local address IP version");
183 if (m_socket->Bind(m_local) == -1)
184 {
185 NS_FATAL_ERROR("Failed to bind socket");
186 }
187 }
188 else
189 {
191 {
192 if (m_socket->Bind() == -1)
193 {
194 NS_FATAL_ERROR("Failed to bind socket");
195 }
196 }
198 {
199 if (m_socket->Bind6() == -1)
200 {
201 NS_FATAL_ERROR("Failed to bind socket");
202 }
203 }
204 else
205 {
206 NS_ASSERT_MSG(false, "Incompatible address type: " << m_peer);
207 }
208 }
209 m_socket->SetIpTos(m_tos); // Affects only IPv4 sockets.
213 }
214
215#ifdef NS3_LOG_ENABLE
216 std::stringstream peerAddressStringStream;
218 {
219 peerAddressStringStream << InetSocketAddress::ConvertFrom(m_peer).GetIpv4() << ":"
221 ;
222 }
224 {
225 peerAddressStringStream << Inet6SocketAddress::ConvertFrom(m_peer).GetIpv6() << ":"
227 }
228 m_peerString = peerAddressStringStream.str();
229#endif // NS3_LOG_ENABLE
230
232}
233
234void
240
241void
243{
244 NS_LOG_FUNCTION(this);
246
247 Address from;
248 Address to;
249 m_socket->GetSockName(from);
251 SeqTsHeader seqTs;
252 seqTs.SetSeq(m_sent);
254 auto p = Create<Packet>(m_size - seqTs.GetSerializedSize());
255
256 // Trace before adding header, for consistency with PacketSink
257 m_txTrace(p);
258 m_txTraceWithAddresses(p, from, to);
259
260 p->AddHeader(seqTs);
261
262 if ((m_socket->Send(p)) >= 0)
263 {
264 ++m_sent;
265 m_totalTx += p->GetSize();
266#ifdef NS3_LOG_ENABLE
267 NS_LOG_INFO("TraceDelay TX " << m_size << " bytes to " << m_peerString << " Uid: "
268 << p->GetUid() << " Time: " << (Simulator::Now()).As(Time::S));
269#endif // NS3_LOG_ENABLE
270 }
271#ifdef NS3_LOG_ENABLE
272 else
273 {
274 NS_LOG_INFO("Error while sending " << m_size << " bytes to " << m_peerString);
275 }
276#endif // NS3_LOG_ENABLE
277
278 if (m_sent < m_count || m_count == 0)
279 {
281 }
282}
283
284uint64_t
286{
287 return m_totalTx;
288}
289
290} // Namespace ns3
a polymophic address class
Definition address.h:90
bool IsInvalid() const
Definition address.cc:60
AttributeValue implementation for Address.
Definition address.h:275
Ptr< Node > GetNode() const
bool IsExpired() const
This method is syntactic sugar for the ns3::Simulator::IsExpired method.
Definition event-id.cc:58
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.
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 bool IsMatchingType(const Address &address)
static bool IsMatchingType(const Address &address)
If the Address matches the type.
Smart pointer class similar to boost::intrusive_ptr.
Packet header to carry sequence number and timestamp.
void SetSeq(uint32_t seq)
uint32_t GetSerializedSize() const override
static EventId Schedule(const Time &delay, FUNC f, Ts &&... args)
Schedule an event to expire after delay.
Definition simulator.h:561
static void Cancel(const EventId &id)
Set the cancel bit on this event: the event's associated function will not be invoked when it expires...
Definition simulator.cc:274
static Time Now()
Return the current simulation virtual time.
Definition simulator.cc:197
virtual int Send(Ptr< Packet > p, uint32_t flags)=0
Send data (or dummy data) to the remote host.
void SetIpTos(uint8_t ipTos)
Manually set IP Type of Service field.
Definition socket.cc:423
virtual bool SetAllowBroadcast(bool allowBroadcast)=0
Configure whether broadcast datagram transmissions are allowed.
virtual int Bind6()=0
Allocate a local IPv6 endpoint for this socket.
virtual int GetPeerName(Address &address) const =0
Get the peer address of a connected socket.
virtual int Connect(const Address &address)=0
Initiate a connection to a remote host.
virtual int GetSockName(Address &address) const =0
Get socket address.
void SetRecvCallback(Callback< void, Ptr< Socket > > receivedData)
Notify application when new data is available to be read.
Definition socket.cc:117
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:61
virtual int Bind(const Address &address)=0
Allocate a local endpoint for this socket.
Base class for source applications.
Address m_local
Local address to bind to.
uint8_t m_tos
The packets Type of Service.
Address m_peer
Peer address.
@ S
second
Definition nstime.h:105
AttributeValue implementation for Time.
Definition nstime.h:1432
a unique identifier for an interface.
Definition type-id.h:49
static TypeId LookupByName(std::string name)
Get a TypeId by name.
Definition type-id.cc:872
TypeId SetParent(TypeId tid)
Set the parent TypeId.
Definition type-id.cc:1001
@ DEPRECATED
Attribute or trace source is deprecated; user is warned.
A Udp client.
Definition udp-client.h:38
Time m_interval
Packet inter-send time.
Definition udp-client.h:99
std::optional< uint16_t > m_peerPort
Remote peer port (deprecated) // NS_DEPRECATED_3_44.
Definition udp-client.h:105
uint64_t GetTotalTx() const
uint64_t m_totalTx
Total bytes sent.
Definition udp-client.h:103
~UdpClient() override
Definition udp-client.cc:99
std::string m_peerString
Remote peer address string.
Definition udp-client.h:109
uint32_t m_sent
Counter for sent packets.
Definition udp-client.h:102
Ptr< Socket > m_socket
Socket.
Definition udp-client.h:104
void SetPort(uint16_t port)
Set the remote port (temporary function until deprecated attributes are removed)
TracedCallback< Ptr< const Packet >, const Address &, const Address & > m_txTraceWithAddresses
Callbacks for tracing the packet Tx events, includes source and destination addresses.
Definition udp-client.h:96
static constexpr uint16_t DEFAULT_PORT
default port
Definition udp-client.h:49
void Send()
Send a packet.
static TypeId GetTypeId()
Get the type ID.
Definition udp-client.cc:34
EventId m_sendEvent
Event to send the next packet.
Definition udp-client.h:106
uint32_t m_size
Size of the sent packet (including the SeqTsHeader)
Definition udp-client.h:100
uint32_t m_count
Maximum number of packets the application will send.
Definition udp-client.h:98
uint16_t GetPort() const
Get the remote port (temporary function until deprecated attributes are removed)
Address GetRemote() const
Get the remote address (temporary function until deprecated attributes are removed)
TracedCallback< Ptr< const Packet > > m_txTrace
Traced Callback: transmitted packets.
Definition udp-client.h:93
void StartApplication() override
Application specific startup code.
void StopApplication() override
Application specific shutdown code.
void SetRemote(const Address &ip, uint16_t port)
set the remote address and port
Hold an unsigned integer type.
Definition uinteger.h:34
uint16_t port
Definition dsdv-manet.cc:33
#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_ASSERT_MSG(condition, message)
At runtime, in debugging builds, if this condition is not true, the program prints the message to out...
Definition assert.h:75
Ptr< const AttributeChecker > MakeAddressChecker()
Definition address.cc:169
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:275
Ptr< const AttributeAccessor > MakeTimeAccessor(T1 a1)
Create an AttributeAccessor for a class data member, or a lone class get functor or set method.
Definition nstime.h:1433
Ptr< const AttributeChecker > MakeTimeChecker()
Helper to make an unbounded Time checker.
Definition nstime.h:1453
Ptr< const AttributeChecker > MakeUintegerChecker()
Definition uinteger.h:85
Ptr< const AttributeAccessor > MakeUintegerAccessor(T1 a1)
Create an AttributeAccessor for a class data member, or a lone class get functor or set method.
Definition uinteger.h:35
Callback< R, Args... > MakeNullCallback()
Definition callback.h:727
#define NS_FATAL_ERROR(msg)
Report a fatal error with a message and terminate.
#define NS_ABORT_MSG_IF(cond, msg)
Abnormal program termination if a condition is true, with a message.
Definition abort.h:97
#define NS_ABORT_IF(cond)
Abnormal program termination if a condition is true.
Definition abort.h:65
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition log.h:191
#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:264
#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 Seconds(double value)
Construct a Time in the indicated unit.
Definition nstime.h:1345
Ptr< const TraceSourceAccessor > MakeTraceSourceAccessor(T a)
Create a TraceSourceAccessor which will control access to the underlying trace source.
Address ConvertToSocketAddress(const Address &address, uint16_t port)
Convert IPv4/IPv6 address with port to a socket address.
Every class exported by the ns3 library is enclosed in the ns3 namespace.