Mbed OS Reference
Loading...
Searching...
No Matches
Socket.h
Go to the documentation of this file.
1/*
2 * Copyright (c) 2015 ARM Limited
3 * SPDX-License-Identifier: Apache-2.0
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18/** @file Socket.h Abstract Socket interface */
19/** @addtogroup NetSocket
20 * Mbed OS Socket API
21 * @{ */
22
23#ifndef SOCKET_H
24#define SOCKET_H
25
27#include "Callback.h"
28#include "rtos/Kernel.h"
29
30/** Socket interface.
31 *
32 * This class defines the Mbed OS Socket API.
33 * Socket is an abstract interface for communicating with remote endpoints.
34 *
35 * This API is intended for applications and libraries instead of
36 * protocol-specific implementations. For example, TCPSocket
37 * and UDPSocket are implementations of the Socket interface.
38 * Socket API is intentionally not protocol-specific, and allows all protocol
39 * to provide the same API regardless of the underlying transport mechanism.
40 */
41class Socket {
42public:
43 /** Destroy a socket.
44 *
45 * Closes socket if the socket is still open.
46 */
47 virtual ~Socket() = default;
48
49 /** Closes the socket.
50 *
51 * Closes any open connection and deallocates any memory associated
52 * with the socket. Called from destructor if socket is not closed.
53 *
54 * If this socket was allocated by an accept() call, then calling this will also delete
55 * the socket object itself.
56 *
57 * @return NSAPI_ERROR_OK on success.
58 * Negative subclass-dependent error code on failure.
59 */
60 virtual nsapi_error_t close() = 0;
61
62 /** Connects socket to a remote address.
63 *
64 * Attempts to make connection on connection-mode protocol or set or reset
65 * the peer address on connectionless protocol.
66 *
67 * Connectionless protocols also use the connected address to filter
68 * incoming packets for recv() and recvfrom() calls.
69 *
70 * To reset the peer address, there must be zero initialized(default constructor) SocketAddress
71 * objects in the address parameter.
72 *
73 * @note If connect() fails it is recommended to close the Socket and create
74 * a new one before attempting to reconnect.
75 *
76 * @param address The SocketAddress of the remote peer.
77 * @return NSAPI_ERROR_OK on success.
78 * Negative subclass-dependent error code on failure.
79 */
80 virtual nsapi_error_t connect(const SocketAddress &address) = 0;
81
82 /** Send data on a socket
83 *
84 * The socket must be connected to a remote host before send() call.
85 * Returns the number of bytes sent from the buffer.
86 * In case of connectionless socket, sends data to pre-specified remote.
87 *
88 * By default, send blocks until all data is sent. If socket is set to
89 * non-blocking or times out, a partial amount can be written.
90 * NSAPI_ERROR_WOULD_BLOCK is returned if no data was written.
91 *
92 * @param data Buffer of data to send to the host.
93 * @param size Size of the buffer in bytes.
94 * @return NSAPI_ERROR_OK on success.
95 * Negative subclass-dependent error code on failure.
96 */
97 virtual nsapi_size_or_error_t send(const void *data, nsapi_size_t size) = 0;
98
99 /** Receive data from a socket.
100 *
101 * Receive data from connected socket, or in the case of connectionless socket,
102 * equivalent to calling recvfrom(NULL, data, size).
103 *
104 * If socket is connected, only packets coming from connected peer address
105 * are accepted.
106 *
107 * @note recv() is allowed write to data buffer even if an error occurs.
108 *
109 * By default, recv blocks until some data is received. If socket is set to
110 * non-blocking or times out, NSAPI_ERROR_WOULD_BLOCK can be returned to
111 * indicate no data.
112 *
113 * @param data Destination buffer for data received from the host.
114 * @param size Size of the buffer in bytes.
115 * @return Number of received bytes on success, negative, subclass-dependent
116 * error code on failure. If no data is available to be received
117 * and the peer has performed an orderly shutdown,
118 * recv() returns 0.
119 */
120 virtual nsapi_size_or_error_t recv(void *data, nsapi_size_t size) = 0;
121
122 /** Send a message on a socket.
123 *
124 * The sendto() function sends a message through a connection-mode or connectionless-mode socket.
125 * If the socket is a connectionless-mode socket, the message is sent to the address specified.
126 * If the socket is a connected-mode socket, address is ignored.
127 *
128 * By default, sendto blocks until data is sent. If socket is set to
129 * non-blocking or times out, NSAPI_ERROR_WOULD_BLOCK is returned
130 * immediately.
131 *
132 * @param address Remote address
133 * @param data Buffer of data to send to the host
134 * @param size Size of the buffer in bytes
135 * @return Number of sent bytes on success, negative subclass-dependent error
136 * code on failure
137 */
139 const void *data, nsapi_size_t size) = 0;
140
141 /** Receive a data from a socket
142 *
143 * Receives a data and stores the source address in address if address
144 * is not NULL. Returns the number of bytes written into the buffer.
145 *
146 * If socket is connected, only packets coming from connected peer address
147 * are accepted.
148 *
149 * @note recvfrom() is allowed write to address and data buffers even if error occurs.
150 *
151 * By default, recvfrom blocks until a datagram is received. If socket is set to
152 * non-blocking or times out with no data, NSAPI_ERROR_WOULD_BLOCK
153 * is returned.
154 *
155 * @param address Destination for the source address or NULL
156 * @param data Destination buffer for datagram received from the host
157 * @param size Size of the buffer in bytes
158 * @return Number of received bytes on success, negative subclass-dependent
159 * error code on failure
160 */
162 void *data, nsapi_size_t size) = 0;
163
164 /** Send a message on a socket.
165 *
166 * The sendto_control() function sends a message through a connection-mode or connectionless-mode socket.
167 * If the socket is a connectionless-mode socket, the message is sent to the address specified.
168 * If the socket is a connected-mode socket, address is ignored.
169 *
170 * Additional control information can be passed to the stack for specific operations.
171 *
172 * By default, sendto blocks until data is sent. If socket is set to
173 * non-blocking or times out, NSAPI_ERROR_WOULD_BLOCK is returned
174 * immediately.
175 *
176 * @param address Remote address
177 * @param data Buffer of data to send to the host
178 * @param size Size of the buffer in bytes
179 * @param control Control data, for instance a populated #nsapi_pktinfo structure.
180 * @param control_size Size of \c control in bytes.
181 * @return Number of sent bytes on success, negative subclass-dependent error
182 * code on failure
183 */
185 const void *data, nsapi_size_t size,
186 nsapi_msghdr_t *control, nsapi_size_t control_size) = 0;
187
188
189 /** Receive a data from a socket
190 *
191 * Receives a data and stores the source address in address if address
192 * is not NULL. Returns the number of bytes written into the buffer.
193 *
194 * If socket is connected, only packets coming from connected peer address
195 * are accepted.
196 *
197 * Ancillary data is stored into \c control. The caller needs to allocate a buffer
198 * that is large enough to contain the data they want to receive, then pass the pointer in
199 * through the \c control member. The data will be filled into \c control, beginning with a header
200 * specifying what data was received. See #MsgHeaderIterator for how to parse this data.
201 *
202 * @note recvfrom_control() is allowed write to address and data buffers even if error occurs.
203 *
204 * By default, recvfrom blocks until a datagram is received. If socket is set to
205 * non-blocking or times out with no data, NSAPI_ERROR_WOULD_BLOCK
206 * is returned.
207 *
208 * @param address Destination for the source address or NULL
209 * @param data Destination buffer for datagram received from the host
210 * @param size Size of the buffer in bytes
211 * @param control Caller-allocated buffer to store ancillary data.
212 * @param control_size Size of the \c control buffer that the caller has allocated.
213 * @return Number of received bytes on success, negative subclass-dependent
214 * error code on failure
215 */
217 void *data, nsapi_size_t size,
218 nsapi_msghdr_t *control, nsapi_size_t control_size) = 0;
219
220 /** Bind a specific address to a socket.
221 *
222 * Binding a socket specifies the address and port on which to receive
223 * data. If the IP address is zeroed, only the port is bound.
224 *
225 * @param address Local address to bind.
226 * @return NSAPI_ERROR_OK on success, negative subclass-dependent error
227 * code on failure.
228 */
229 virtual nsapi_error_t bind(const SocketAddress &address) = 0;
230
231 /** Set blocking or non-blocking mode of the socket.
232 *
233 * Initially all sockets are in blocking mode. In non-blocking mode
234 * blocking operations such as send/recv/accept return
235 * NSAPI_ERROR_WOULD_BLOCK if they cannot continue.
236 *
237 * set_blocking(false) is equivalent to set_timeout(0)
238 * set_blocking(true) is equivalent to set_timeout(-1)
239 *
240 * @param blocking true for blocking mode, false for non-blocking mode.
241 */
242 virtual void set_blocking(bool blocking) = 0;
243
244 /**
245 * @brief Set timeout on blocking socket operations.
246 *
247 * Initially all sockets have unbounded timeouts. NSAPI_ERROR_WOULD_BLOCK
248 * is returned if a blocking operation takes longer than the specified
249 * timeout. A timeout of 0 removes the timeout from the socket. A negative
250 * value gives the socket an unbounded timeout.
251 *
252 * set_timeout(0) is equivalent to set_blocking(false)
253 * set_timeout(-1) is equivalent to set_blocking(true)
254 *
255 * @param timeout Timeout in milliseconds
256 */
257 virtual void set_timeout(int timeout) = 0;
258
259 /**
260 * @brief Set timeout on blocking socket operations.
261 *
262 * Initially all sockets have unbounded timeouts. NSAPI_ERROR_WOULD_BLOCK
263 * is returned if a blocking operation takes longer than the specified
264 * timeout. A timeout of 0 removes the timeout from the socket. A negative
265 * value gives the socket an unbounded timeout.
266 *
267 * set_timeout(0ms) is equivalent to set_blocking(false)
268 * set_timeout(-1ms) is equivalent to set_blocking(true)
269 *
270 * @param timeout Timeout in milliseconds
271 */
272 void set_timeout(const rtos::Kernel::Clock::duration timeout)
273 {
274 set_timeout(static_cast<int>(timeout.count()));
275 }
276
277 /** Register a callback on state change of the socket.
278 *
279 * The specified callback is called on state changes, such as when
280 * the socket can receive/send/accept successfully and when an error
281 * occurs. The callback may also be called spuriously without reason.
282 *
283 * The callback may be called in an interrupt context and should not
284 * perform expensive operations such as receive/send calls.
285 *
286 * Note! This is not intended as a replacement for a poll or attach-like
287 * asynchronous API, but rather as a building block for constructing
288 * such functionality. The exact timing of the registered function
289 * is not guaranteed and susceptible to change.
290 *
291 * @param func Function to call on state change.
292 */
293 virtual void sigio(mbed::Callback<void()> func) = 0;
294
295 /** Set socket options.
296 *
297 * setsockopt() allows an application to pass stack-specific options
298 * to the underlying stack using stack-specific level and option names,
299 * or to request generic options using levels from nsapi_socket_level_t.
300 *
301 * For unsupported options, NSAPI_ERROR_UNSUPPORTED is returned
302 * and the socket is unmodified.
303 *
304 * @param level Stack-specific protocol level or nsapi_socket_level_t.
305 * @param optname Level-specific option name.
306 * @param optval Option value.
307 * @param optlen Length of the option value.
308 * @retval NSAPI_ERROR_OK on success.
309 * @retval NSAPI_ERROR_NO_SOCKET if socket is not open.
310 * @retval Negative error code on failure, see #NetworkStack::setsockopt
311 */
312 virtual nsapi_error_t setsockopt(int level, int optname, const void *optval, unsigned optlen) = 0;
313
314 /** Get socket options.
315 *
316 * getsockopt() allows an application to retrieve stack-specific options
317 * from the underlying stack using stack-specific level and option names,
318 * or to request generic options using levels from nsapi_socket_level_t.
319 *
320 * For unsupported options, NSAPI_ERROR_UNSUPPORTED is returned
321 * and the socket is unmodified.
322 *
323 * @param level Stack-specific protocol level or nsapi_socket_level_t.
324 * @param optname Level-specific option name.
325 * @param optval Destination for option value.
326 * @param optlen Length of the option value.
327 * @retval NSAPI_ERROR_OK on success.
328 * @retval NSAPI_ERROR_NO_SOCKET if socket is not open.
329 * @retval Negative error code on failure, see #NetworkStack::getsockopt
330 */
331 virtual nsapi_error_t getsockopt(int level, int optname, void *optval, unsigned *optlen) = 0;
332
333 /**
334 * @brief Waits for a client to try to connect to this socket, then returns a socket for the new connection.
335 *
336 * On error, returns nullptr and sets the error code parameter (if provided).
337 *
338 * Note that if a socket is returned, you must eventually call close() on it to release its resources.
339 * Calling close() will also delete the socket object, no separate \c delete is required.
340 * Referencing the returned socket after a close() call is not allowed and leads to undefined behavior.
341 *
342 * By default, this function blocks until an incoming connection occurs. If socket is set to
343 * non-blocking or times out, an \c NSAPI_ERROR_WOULD_BLOCK error is returned.
344 *
345 * @param error If you wish to check the error code, pass an error code pointer here.
346 * @return Pointer to a socket, or nullptr on error
347 */
348 virtual Socket *accept(nsapi_error_t *error = nullptr) = 0;
349
350 /** Listen for incoming connections.
351 *
352 * Marks the socket as a passive socket that can be used to accept
353 * incoming connections.
354 *
355 * @param backlog Number of pending connections that can be queued
356 * simultaneously, defaults to 1.
357 * @return NSAPI_ERROR_OK on success, negative error code on failure.
358 */
359 virtual nsapi_error_t listen(int backlog = 1) = 0;
360
361 /** Get the remote-end peer associated with this socket.
362 *
363 * Copy the remote peer address to a SocketAddress structure pointed by
364 * address parameter. Socket must be connected to have a peer address
365 * associated.
366 *
367 * @param address Pointer to SocketAddress structure.
368 * @retval NSAPI_ERROR_OK on success.
369 * @retval NSAPI_ERROR_NO_SOCKET if socket is not connected.
370 * @retval NSAPI_ERROR_NO_CONNECTION if the remote peer was not set.
371 */
373};
374
375
376#endif
377
378/** @}*/
SocketAddress class.
Representation of an IP (v4 or v6) address and port pair.
Socket interface.
Definition Socket.h:41
virtual nsapi_error_t setsockopt(int level, int optname, const void *optval, unsigned optlen)=0
Set socket options.
virtual Socket * accept(nsapi_error_t *error=nullptr)=0
Waits for a client to try to connect to this socket, then returns a socket for the new connection.
virtual nsapi_size_or_error_t recvfrom_control(SocketAddress *address, void *data, nsapi_size_t size, nsapi_msghdr_t *control, nsapi_size_t control_size)=0
Receive a data from a socket.
virtual nsapi_size_or_error_t sendto_control(const SocketAddress &address, const void *data, nsapi_size_t size, nsapi_msghdr_t *control, nsapi_size_t control_size)=0
Send a message on a socket.
virtual nsapi_error_t close()=0
Closes the socket.
virtual nsapi_error_t bind(const SocketAddress &address)=0
Bind a specific address to a socket.
void set_timeout(const rtos::Kernel::Clock::duration timeout)
Set timeout on blocking socket operations.
Definition Socket.h:272
virtual void sigio(mbed::Callback< void()> func)=0
Register a callback on state change of the socket.
virtual ~Socket()=default
Destroy a socket.
virtual nsapi_size_or_error_t recvfrom(SocketAddress *address, void *data, nsapi_size_t size)=0
Receive a data from a socket.
virtual nsapi_error_t getsockopt(int level, int optname, void *optval, unsigned *optlen)=0
Get socket options.
virtual nsapi_error_t getpeername(SocketAddress *address)=0
Get the remote-end peer associated with this socket.
virtual nsapi_error_t connect(const SocketAddress &address)=0
Connects socket to a remote address.
virtual nsapi_size_or_error_t sendto(const SocketAddress &address, const void *data, nsapi_size_t size)=0
Send a message on a socket.
virtual nsapi_error_t listen(int backlog=1)=0
Listen for incoming connections.
virtual void set_timeout(int timeout)=0
Set timeout on blocking socket operations.
virtual nsapi_size_or_error_t send(const void *data, nsapi_size_t size)=0
Send data on a socket.
virtual nsapi_size_or_error_t recv(void *data, nsapi_size_t size)=0
Receive data from a socket.
virtual void set_blocking(bool blocking)=0
Set blocking or non-blocking mode of the socket.
Callback class based on template specialization.
Definition Callback.h:53
signed int nsapi_size_or_error_t
Type used to represent either a size or error passed through sockets.
signed int nsapi_error_t
Type used to represent error codes.
unsigned int nsapi_size_t
Type used to represent the size of data passed through sockets.
MBED_NORETURN void error(const char *format,...) MBED_PRINTF(1
To generate a fatal compile-time error, you can use the pre-processor error directive.
Header structure for control info.