1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
3 * Copyright (c) 2006 Georgia Tech Research Corporation
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License version 2 as
8 * published by the Free Software Foundation;
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 * Authors: George F. Riley<riley@ece.gatech.edu>
20 * Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
26 #include "ns3/callback.h"
29 #include "ns3/object.h"
41 * \defgroup socket Socket
45 * \brief A low-level Socket API based loosely on the BSD Socket API.
48 * A few things to keep in mind about this type of socket:
49 * - it uses ns-3 API constructs such as class ns3::Address instead of
51 * - in contrast to the original BSD socket API, this API is asynchronous:
52 * it does not contain blocking calls. Sending and receiving operations
53 * must make use of the callbacks provided.
54 * - It also uses class ns3::Packet as a fancy byte buffer, allowing
55 * data to be passed across the API using an ns-3 Packet instead of
57 * - Not all of the full POSIX sockets API is supported
59 * Other than that, it tries to stick to the BSD API to make it
60 * easier for those who know the BSD API to use this API.
61 * More details are provided in the ns-3 tutorial.
63 class Socket : public Object
68 virtual ~Socket (void);
86 * This method wraps the creation of sockets that is performed
87 * by a socket factory on a given node based on a TypeId.
89 * \return A smart pointer to a newly created socket.
91 * \param node The node on which to create the socket
92 * \param tid The TypeId of the socket to create
94 static Ptr<Socket> CreateSocket (Ptr<Node> node, TypeId tid);
96 * \return the errno associated to the last call which failed in this
97 * socket. Each socket's errno is initialized to zero
98 * when the socket is created.
100 virtual enum Socket::SocketErrno GetErrno (void) const = 0;
102 * \returns the node this socket is associated with.
104 virtual Ptr<Node> GetNode (void) const = 0;
106 * \param connectionSucceeded this callback is invoked when the
107 * connection request initiated by the user is successfully
108 * completed. The callback is passed back a pointer to
109 * the same socket object.
110 * \param connectionFailed this callback is invoked when the
111 * connection request initiated by the user is unsuccessfully
112 * completed. The callback is passed back a pointer to the
113 * same socket object.
115 void SetConnectCallback (Callback<void, Ptr<Socket> > connectionSucceeded,
116 Callback<void, Ptr<Socket> > connectionFailed);
118 * \brief Accept connection requests from remote hosts
119 * \param connectionRequest Callback for connection request from peer.
120 * This user callback is passed a pointer to this socket, the
121 * ip address and the port number of the connection originator.
122 * This callback must return true to accept the incoming connection,
123 * false otherwise. If the connection is accepted, the
124 * "newConnectionCreated" callback will be invoked later to
125 * give access to the user to the socket created to match
126 * this new connection. If the user does not explicitly
127 * specify this callback, all incoming connections will be refused.
128 * \param newConnectionCreated Callback for new connection: when a new
129 * is accepted, it is created and the corresponding socket is passed
130 * back to the user through this callback. This user callback is
131 * passed a pointer to the new socket, and the ip address and
132 * port number of the connection originator.
134 void SetAcceptCallback (Callback<bool, Ptr<Socket>,
135 const Address &> connectionRequest,
136 Callback<void, Ptr<Socket>,
137 const Address&> newConnectionCreated);
139 * \brief Notify application when a packet has been sent from transport
140 * protocol (non-standard socket call)
141 * \param dataSent Callback for the event that data is sent from the
142 * underlying transport protocol. This callback is passed a
143 * pointer to the socket, and the number of bytes sent.
145 void SetDataSentCallback (Callback<void, Ptr<Socket>,
148 * \brief Notify application when space in transmit buffer is added
150 * This callback is intended to notify a
151 * socket that would have been blocked in a blocking socket model
152 * that space is available in the transmit buffer and that it
153 * can call Send() again.
155 * \param sendCb Callback for the event that the socket transmit buffer
156 * fill level has decreased. This callback is passed a pointer to
157 * the socket, and the number of bytes available for writing
158 * into the buffer (an absolute value). If there is no transmit
159 * buffer limit, a maximum-sized integer is always returned.
161 void SetSendCallback (Callback<void, Ptr<Socket>, uint32_t> sendCb);
163 * \brief Notify application when new data is available to be read.
165 * This callback is intended to notify a socket that would
166 * have been blocked in a blocking socket model that data
167 * is available to be read.
169 void SetRecvCallback (Callback<void, Ptr<Socket> >);
171 * \param address the address to try to allocate
172 * \returns 0 on success, -1 on failure.
174 * Allocate a local endpoint for this socket.
176 virtual int Bind (const Address &address) = 0;
179 * Allocate a local endpoint for this socket.
181 * \returns 0 on success, -1 on failure.
183 virtual int Bind () = 0;
186 * \brief Close a socket.
187 * \returns zero on success, -1 on failure.
189 * After the Close call, the socket is no longer valid, and cannot
190 * safely be used for subsequent operations.
192 virtual int Close (void) = 0;
195 * \returns zero on success, -1 on failure.
197 * Do not allow any further Send calls. This method is typically
198 * implemented for Tcp sockets by a half close.
200 virtual int ShutdownSend (void) = 0;
203 * \returns zero on success, -1 on failure.
205 * Do not allow any further Recv calls. This method is typically
206 * implemented for Tcp sockets by a half close.
208 virtual int ShutdownRecv (void) = 0;
211 * \brief Initiate a connection to a remote host
212 * \param address Address of remote.
214 virtual int Connect (const Address &address) = 0;
217 * \brief Listen for incoming connections.
218 * \returns 0 on success, -1 on error (in which case errno is set).
220 virtual int Listen (void) = 0;
223 * \brief Returns the number of bytes which can be sent in a single call
226 * For datagram sockets, this returns the number of bytes that
227 * can be passed atomically through the underlying protocol.
229 * For stream sockets, this returns the available space in bytes
230 * left in the transmit buffer.
232 virtual uint32_t GetTxAvailable (void) const = 0;
235 * \brief Send data (or dummy data) to the remote host
237 * This function matches closely in semantics to the send() function
238 * call in the standard C library (libc):
239 * ssize_t send (int s, const void *msg, size_t len, int flags);
240 * except that the send I/O is asynchronous. This is the
241 * primary Send method at this low-level API and must be implemented
244 * In a typical blocking sockets model, this call would block upon
245 * lack of space to hold the message to be sent. In ns-3 at this
246 * API, the call returns immediately in such a case, but the callback
247 * registered with SetSendCallback() is invoked when the socket
248 * has space (when it conceptually unblocks); this is an asynchronous
249 * I/O model for send().
251 * This variant of Send() uses class ns3::Packet to encapsulate
252 * data, rather than providing a raw pointer and length field.
253 * This allows an ns-3 application to attach tags if desired (such
254 * as a flow ID) and may allow the simulator to avoid some data
255 * copies. Despite the appearance of sending Packets on a stream
256 * socket, just think of it as a fancy byte buffer with streaming
259 * If either the message buffer within the Packet is too long to pass
260 * atomically through the underlying protocol (for datagram sockets),
261 * or the message buffer cannot entirely fit in the transmit buffer
262 * (for stream sockets), -1 is returned and SocketErrno is set
263 * to ERROR_MSGSIZE. If the packet does not fit, the caller can
264 * split the Packet (based on information obtained from
265 * GetTxAvailable) and reattempt to send the data.
267 * The flags argument is formed by or'ing one or more of the values:
268 * MSG_OOB process out-of-band data
269 * MSG_DONTROUTE bypass routing, use direct interface
270 * These flags are _unsupported_ as of ns-3.1.
272 * \param p ns3::Packet to send
273 * \param flags Socket control flags
274 * \returns the number of bytes accepted for transmission if no error
275 * occurs, and -1 otherwise.
277 * \see SetSendCallback
279 virtual int Send (Ptr<Packet> p, uint32_t flags) = 0;
282 * \brief Send data to a specified peer.
284 * This method has similar semantics to Send () but subclasses may
285 * want to provide checks on socket state, so the implementation is
286 * pushed to subclasses.
288 * \param p packet to send
289 * \param flags Socket control flags
290 * \param toAddress IP Address of remote host
291 * \returns -1 in case of error or the number of bytes copied in the
292 * internal buffer and accepted for transmission.
294 virtual int SendTo (Ptr<Packet> p, uint32_t flags,
295 const Address &toAddress) = 0;
298 * Return number of bytes which can be returned from one or
299 * multiple calls to Recv.
300 * Must be possible to call this method from the Recv callback.
302 virtual uint32_t GetRxAvailable (void) const = 0;
305 * \brief Read data from the socket
307 * This function matches closely in semantics to the recv() function
308 * call in the standard C library (libc):
309 * ssize_t recv (int s, void *buf, size_t len, int flags);
310 * except that the receive I/O is asynchronous. This is the
311 * primary Recv method at this low-level API and must be implemented
314 * This method is normally used only on a connected socket.
315 * In a typical blocking sockets model, this call would block until
316 * at least one byte is returned or the connection closes.
317 * In ns-3 at this API, the call returns immediately in such a case
318 * and returns 0 if nothing is available to be read.
319 * However, an application can set a callback, ns3::SetRecvCallback,
320 * to be notified of data being available to be read
321 * (when it conceptually unblocks); this is an asynchronous
322 * I/O model for recv().
324 * This variant of Recv() uses class ns3::Packet to encapsulate
325 * data, rather than providing a raw pointer and length field.
326 * This allows an ns-3 application to attach tags if desired (such
327 * as a flow ID) and may allow the simulator to avoid some data
328 * copies. Despite the appearance of receiving Packets on a stream
329 * socket, just think of it as a fancy byte buffer with streaming
332 * The semantics depend on the type of socket. For a datagram socket,
333 * each Recv() returns the data from at most one Send(), and order
334 * is not necessarily preserved. For a stream socket, the bytes
335 * are delivered in order, and on-the-wire packet boundaries are
338 * The flags argument is formed by or'ing one or more of the values:
339 * MSG_OOB process out-of-band data
340 * MSG_PEEK peek at incoming message
341 * None of these flags are supported for now.
343 * Some variants of Recv() are supported as additional API,
344 * including RecvFrom(), overloaded Recv() without arguments,
345 * and variants that use raw character buffers.
347 * \param maxSize reader will accept packet up to maxSize
348 * \param flags Socket control flags
349 * \returns Ptr<Packet> of the next in-sequence packet. Returns
350 * 0 if the socket cannot return a next in-sequence packet conforming
351 * to the maxSize and flags.
353 * \see SetRecvCallback
355 virtual Ptr<Packet> Recv (uint32_t maxSize, uint32_t flags) = 0;
358 * \brief Read a single packet from the socket and retrieve the sender
361 * Calls Recv(maxSize, flags) with maxSize
362 * implicitly set to maximum sized integer, and flags set to zero.
364 * This method has similar semantics to Recv () but subclasses may
365 * want to provide checks on socket state, so the implementation is
366 * pushed to subclasses.
368 * \param maxSize reader will accept packet up to maxSize
369 * \param flags Socket control flags
370 * \param fromAddress output parameter that will return the
371 * address of the sender of the received packet, if any. Remains
372 * untouched if no packet is received.
373 * \returns Ptr<Packet> of the next in-sequence packet. Returns
374 * 0 if the socket cannot return a next in-sequence packet.
376 virtual Ptr<Packet> RecvFrom (uint32_t maxSize, uint32_t flags,
377 Address &fromAddress) = 0;
379 /////////////////////////////////////////////////////////////////////
380 // The remainder of these public methods are overloaded methods //
381 // or variants of Send() and Recv(), and they are non-virtual //
382 /////////////////////////////////////////////////////////////////////
385 * \brief Send data (or dummy data) to the remote host
387 * Overloaded version of Send(..., flags) with flags set to zero.
389 * \param p ns3::Packet to send
390 * \returns the number of bytes accepted for transmission if no error
391 * occurs, and -1 otherwise.
393 int Send (Ptr<Packet> p);
396 * \brief Send data (or dummy data) to the remote host
398 * This method is provided so as to have an API which is closer in
399 * appearance to that of real network or BSD sockets.
401 * \param buf A pointer to a raw byte buffer of some data to send. If
402 * this buffer is 0, we send dummy data whose size is specified by the
404 * \param size the number of bytes to copy from the buffer
405 * \param flags Socket control flags
407 int Send (const uint8_t* buf, uint32_t size, uint32_t flags);
411 * \brief Send data to a specified peer.
413 * This method is provided so as to have an API which is closer in
414 * appearance to that of real network or BSD sockets.
416 * \param buf A pointer to a raw byte buffer of some data to send.
417 * If this is 0, we send dummy data whose size is specified by the
419 * \param size the number of bytes to copy from the buffer
420 * \param flags Socket control flags
421 * \param address IP Address of remote host
422 * \returns -1 in case of error or the number of bytes copied in the
423 * internal buffer and accepted for transmission.
426 int SendTo (const uint8_t* buf, uint32_t size, uint32_t flags,
427 const Address &address);
430 * \brief Read a single packet from the socket
432 * Overloaded version of Recv(maxSize, flags) with maxSize
433 * implicitly set to maximum sized integer, and flags set to zero.
435 * \returns Ptr<Packet> of the next in-sequence packet. Returns
436 * 0 if the socket cannot return a next in-sequence packet.
438 Ptr<Packet> Recv (void);
441 * \brief Recv data (or dummy data) from the remote host
443 * This method is provided so as to have an API which is closer in
444 * appearance to that of real network or BSD sockets.
446 * If the underlying packet was carring null (fake) data, this buffer
447 * will be zeroed up to the length specified by the return value.
449 * \param buf A pointer to a raw byte buffer to write the data to.
450 * \param size Number of bytes (at most) to copy to buf
451 * \param flags any flags to pass to the socket
452 * \returns number of bytes copied into buf
454 int Recv (uint8_t* buf, uint32_t size, uint32_t flags);
457 * \brief Read a single packet from the socket and retrieve the sender
460 * Calls RecvFrom (maxSize, flags, fromAddress) with maxSize
461 * implicitly set to maximum sized integer, and flags set to zero.
463 * \param fromAddress output parameter that will return the
464 * address of the sender of the received packet, if any. Remains
465 * untouched if no packet is received.
466 * \returns Ptr<Packet> of the next in-sequence packet. Returns
467 * 0 if the socket cannot return a next in-sequence packet.
469 Ptr<Packet> RecvFrom (Address &fromAddress);
472 * \brief Read a single packet from the socket and retrieve the sender
475 * This method is provided so as to have an API which is closer in
476 * appearance to that of real network or BSD sockets.
478 * \param buf A pointer to a raw byte buffer to write the data to.
479 * If the underlying packet was carring null (fake) data, this buffer
480 * will be zeroed up to the length specified by the return value.
481 * \param size Number of bytes (at most) to copy to buf
482 * \param flags any flags to pass to the socket
483 * \param fromAddress output parameter that will return the
484 * address of the sender of the received packet, if any. Remains
485 * untouched if no packet is received.
486 * \returns number of bytes copied into buf
488 int RecvFrom (uint8_t* buf, uint32_t size, uint32_t flags,
489 Address &fromAddress);
491 * \returns the address name this socket is associated with.
493 virtual int GetSockName (Address &address) const = 0;
496 void NotifyConnectionSucceeded (void);
497 void NotifyConnectionFailed (void);
498 bool NotifyConnectionRequest (const Address &from);
499 void NotifyNewConnectionCreated (Ptr<Socket> socket, const Address &from);
500 void NotifyDataSent (uint32_t size);
501 void NotifySend (uint32_t spaceAvailable);
502 void NotifyDataRecv (void);
503 virtual void DoDispose (void);
505 Callback<void, Ptr<Socket> > m_connectionSucceeded;
506 Callback<void, Ptr<Socket> > m_connectionFailed;
507 Callback<bool, Ptr<Socket>, const Address &> m_connectionRequest;
508 Callback<void, Ptr<Socket>, const Address&> m_newConnectionCreated;
509 Callback<void, Ptr<Socket>, uint32_t> m_dataSent;
510 Callback<void, Ptr<Socket>, uint32_t > m_sendCb;
511 Callback<void, Ptr<Socket> > m_receivedData;
516 * \brief This class implements a tag that carries an address
517 * of a packet across the socket interface.
519 class SocketAddressTag : public Tag
523 void SetAddress (Address addr);
524 Address GetAddress (void) const;
526 static TypeId GetTypeId (void);
527 virtual TypeId GetInstanceTypeId (void) const;
528 virtual uint32_t GetSerializedSize (void) const;
529 virtual void Serialize (TagBuffer i) const;
530 virtual void Deserialize (TagBuffer i);
531 virtual void Print (std::ostream &os) const;
538 * \brief This class implements a tag that carries the socket-specific
539 * TTL of a packet to the IP layer
541 class SocketIpTtlTag : public Tag
545 void SetTtl (uint8_t ttl);
546 uint8_t GetTtl (void) const;
548 static TypeId GetTypeId (void);
549 virtual TypeId GetInstanceTypeId (void) const;
550 virtual uint32_t GetSerializedSize (void) const;
551 virtual void Serialize (TagBuffer i) const;
552 virtual void Deserialize (TagBuffer i);
553 virtual void Print (std::ostream &os) const;
561 * \brief indicated whether packets should be sent out with
564 class SocketSetDontFragmentTag : public Tag
567 SocketSetDontFragmentTag ();
570 bool IsEnabled (void) const;
572 static TypeId GetTypeId (void);
573 virtual TypeId GetInstanceTypeId (void) const;
574 virtual uint32_t GetSerializedSize (void) const;
575 virtual void Serialize (TagBuffer i) const;
576 virtual void Deserialize (TagBuffer i);
577 virtual void Print (std::ostream &os) const;
584 #endif /* SOCKET_H */