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 .AddAttribute("RemoteAddress",
53 "The destination Address of the outbound packets",
56 (void(UdpClient::*)(const Address&)) &
57 UdpClient::SetRemote, // this is needed to indicate which version
58 // of the function overload to use
62 "Replaced by Remote in ns-3.44.")
63 .AddAttribute("RemotePort",
64 "The destination port of the outbound packets",
69 "Replaced by Remote in ns-3.44.")
70 .AddAttribute("PacketSize",
71 "Size of packets generated. The minimum packet size is 12 bytes which is "
72 "the size of the header carrying the sequence number and the time stamp.",
73 UintegerValue(1024),
76 .AddTraceSource("Tx",
77 "A new packet is created and sent",
79 "ns3::Packet::TracedCallback")
80 .AddTraceSource("TxWithAddresses",
81 "A new packet is created and sent",
83 "ns3::Packet::TwoAddressTracedCallback");
84 return tid;
85}
86
88 : m_sent{0},
89 m_totalTx{0},
90 m_socket{nullptr},
91 m_peerPort{},
92 m_sendEvent{}
93{
94 NS_LOG_FUNCTION(this);
95}
96
101
102void
104{
105 NS_LOG_FUNCTION(this << ip << port);
106 SetRemote(ip);
107 SetPort(port);
108}
109
110void
112{
113 NS_LOG_FUNCTION(this << addr);
114 if (!addr.IsInvalid())
115 {
116 m_peer = addr;
117 if (m_peerPort)
118 {
120 }
121 }
122}
123
126{
127 return m_peer;
128}
129
130void
132{
133 NS_LOG_FUNCTION(this << port);
134 if (m_peer.IsInvalid())
135 {
136 // save for later
138 return;
139 }
141 {
143 }
144}
145
146uint16_t
163
164void
166{
167 NS_LOG_FUNCTION(this);
168
169 if (!m_socket)
170 {
171 auto tid = TypeId::LookupByName("ns3::UdpSocketFactory");
173 NS_ABORT_MSG_IF(m_peer.IsInvalid(), "Remote address not properly set");
174 if (!m_local.IsInvalid())
175 {
180 "Incompatible peer and local address IP version");
181 if (m_socket->Bind(m_local) == -1)
182 {
183 NS_FATAL_ERROR("Failed to bind socket");
184 }
185 }
186 else
187 {
189 {
190 if (m_socket->Bind() == -1)
191 {
192 NS_FATAL_ERROR("Failed to bind socket");
193 }
194 }
196 {
197 if (m_socket->Bind6() == -1)
198 {
199 NS_FATAL_ERROR("Failed to bind socket");
200 }
201 }
202 else
203 {
204 NS_ASSERT_MSG(false, "Incompatible address type: " << m_peer);
205 }
206 }
207 m_socket->SetIpTos(m_tos); // Affects only IPv4 sockets.
211 }
212
213#ifdef NS3_LOG_ENABLE
214 std::stringstream peerAddressStringStream;
216 {
217 peerAddressStringStream << InetSocketAddress::ConvertFrom(m_peer).GetIpv4() << ":"
219 ;
220 }
222 {
223 peerAddressStringStream << Inet6SocketAddress::ConvertFrom(m_peer).GetIpv6() << ":"
225 }
226 m_peerString = peerAddressStringStream.str();
227#endif // NS3_LOG_ENABLE
228
230}
231
232void
238
239void
241{
242 NS_LOG_FUNCTION(this);
244
245 Address from;
246 Address to;
247 m_socket->GetSockName(from);
249 SeqTsHeader seqTs;
250 seqTs.SetSeq(m_sent);
252 auto p = Create<Packet>(m_size - seqTs.GetSerializedSize());
253
254 // Trace before adding header, for consistency with PacketSink
255 m_txTrace(p);
256 m_txTraceWithAddresses(p, from, to);
257
258 p->AddHeader(seqTs);
259
260 if ((m_socket->Send(p)) >= 0)
261 {
262 ++m_sent;
263 m_totalTx += p->GetSize();
264#ifdef NS3_LOG_ENABLE
265 NS_LOG_INFO("TraceDelay TX " << m_size << " bytes to " << m_peerString << " Uid: "
266 << p->GetUid() << " Time: " << (Simulator::Now()).As(Time::S));
267#endif // NS3_LOG_ENABLE
268 }
269#ifdef NS3_LOG_ENABLE
270 else
271 {
272 NS_LOG_INFO("Error while sending " << m_size << " bytes to " << m_peerString);
273 }
274#endif // NS3_LOG_ENABLE
275
276 if (m_sent < m_count || m_count == 0)
277 {
279 }
280}
281
282uint64_t
284{
285 return m_totalTx;
286}
287
288} // 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:560
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:1431
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:97
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:1432
Ptr< const AttributeChecker > MakeTimeChecker()
Helper to make an unbounded Time checker.
Definition nstime.h:1452
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:1344
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.