sendto function (winsock.h)
The sendto function sends data to a specific destination.
Syntax
Parameters
A descriptor identifying a (possibly connected) socket.
A pointer to a buffer containing the data to be transmitted.
The length, in bytes, of the data pointed to by the buf parameter.
A set of flags that specify the way in which the call is made.
An optional pointer to a sockaddr structure that contains the address of the target socket.
The size, in bytes, of the address pointed to by the to parameter.
Return value
If no error occurs, sendto returns the total number of bytes sent, which can be less than the number indicated by len. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError.
Error code | Meaning |
---|---|
WSANOTINITIALISED | A successful WSAStartup call must occur before using this function. |
WSAENETDOWN | The network subsystem has failed. |
WSAEACCES | The requested address is a broadcast address, but the appropriate flag was not set. Call setsockopt with the SO_BROADCAST parameter to allow the use of the broadcast address. |
WSAEINVAL | An unknown flag was specified, or MSG_OOB was specified for a socket with SO_OOBINLINE enabled. |
WSAEINTR | A blocking Windows Sockets 1.1 call was canceled through WSACancelBlockingCall. |
WSAEINPROGRESS | A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function. |
WSAEFAULT | The buf or to parameters are not part of the user address space, or the tolen parameter is too small. |
WSAENETRESET | The connection has been broken due to keep-alive activity detecting a failure while the operation was in progress. |
WSAENOBUFS | No buffer space is available. |
WSAENOTCONN | The socket is not connected (connection-oriented sockets only). |
WSAENOTSOCK | The descriptor is not a socket. |
WSAEOPNOTSUPP | MSG_OOB was specified, but the socket is not stream-style such as type SOCK_STREAM, OOB data is not supported in the communication domain associated with this socket, or the socket is unidirectional and supports only receive operations. |
WSAESHUTDOWN | The socket has been shut down; it is not possible to sendto on a socket after shutdown has been invoked with how set to SD_SEND or SD_BOTH. |
WSAEWOULDBLOCK | The socket is marked as nonblocking and the requested operation would block. |
WSAEMSGSIZE | The socket is message oriented, and the message is larger than the maximum supported by the underlying transport. |
WSAEHOSTUNREACH | The remote host cannot be reached from this host at this time. |
WSAECONNABORTED | The virtual circuit was terminated due to a time-out or other failure. The application should close the socket as it is no longer usable. |
WSAECONNRESET | The virtual circuit was reset by the remote side executing a hard or abortive close. For UPD sockets, the remote host was unable to deliver a previously sent UDP datagram and responded with a «Port Unreachable» ICMP packet. The application should close the socket as it is no longer usable. |
WSAEADDRNOTAVAIL | The remote address is not a valid address, for example, ADDR_ANY. |
WSAEAFNOSUPPORT | Addresses in the specified family cannot be used with this socket. |
WSAEDESTADDRREQ | A destination address is required. |
WSAENETUNREACH | The network cannot be reached from this host at this time. |
WSAEHOSTUNREACH | A socket operation was attempted to an unreachable host. |
WSAETIMEDOUT | The connection has been dropped, because of a network failure or because the system on the other end went down without notice. |
Remarks
The sendto function is used to write outgoing data on a socket. For message-oriented sockets, care must be taken not to exceed the maximum packet size of the underlying subnets, which can be obtained by using getsockopt to retrieve the value of socket option SO_MAX_MSG_SIZE. If the data is too long to pass atomically through the underlying protocol, the error WSAEMSGSIZE is returned and no data is transmitted.
The to parameter can be any valid address in the socket’s address family, including a broadcast or any multicast address. To send to a broadcast address, an application must have used setsockopt with SO_BROADCAST enabled. Otherwise, sendto will fail with the error code WSAEACCES. For TCP/IP, an application can send to any multicast address (without becoming a group member).
If the socket is not connected, the
getsockname function can be used to determine the local port number associated with the socket but the IP address returned is set to the wildcard address for the given protocol (for example, INADDR_ANY or «0.0.0.0» for IPv4 and IN6ADDR_ANY_INIT or «::» for IPv6).
The successful completion of a sendto does not indicate that the data was successfully delivered.
The sendto function is normally used on a connectionless socket to send a datagram to a specific peer socket identified by the to parameter. Even if the connectionless socket has been previously connected to a specific address, the to parameter overrides the destination address for that particular datagram only. On a connection-oriented socket, the to and tolen parameters are ignored, making sendto equivalent to send.
Example Code
For Sockets Using IP (Version 4)
If the broadcast should be sent out only on a specific interface, then the address pointed to by the to parameter should contain the subnet broadcast address for the interface and the intended port. For example, an IPv4 network address of 192.168.1.0 with a subnet mask of 255.255.255.0 would use a subnet broadcast address of 192.168.1.255.
It is generally inadvisable for a broadcast datagram to exceed the size at which fragmentation can occur, which implies that the data portion of the datagram (excluding headers) should not exceed 512 bytes.
If no buffer space is available within the transport system to hold the data to be transmitted, sendto will block unless the socket has been placed in a nonblocking mode. On nonblocking, stream oriented sockets, the number of bytes written can be between 1 and the requested length, depending on buffer availability on both the client and server systems. The select, WSAAsyncSelect or WSAEventSelect function can be used to determine when it is possible to send more data.
Calling sendto with a len of zero is permissible and will return zero as a valid value. For message-oriented sockets, a zero-length transport datagram is sent.
The flags parameter can be used to influence the behavior of the function invocation beyond the options specified for the associated socket. The semantics of this function are determined by the socket options and the flags parameter. The latter is constructed by using the bitwise OR operator with any of the following values.
Value | Meaning |
---|---|
MSG_DONTROUTE | Specifies that the data should not be subject to routing. A Windows Sockets service provider can choose to ignore this flag. |
MSG_OOB | Sends OOB data (stream-style socket such as SOCK_STREAM only). |
В
WindowsВ PhoneВ 8: This function is supported for Windows Phone Store apps on WindowsВ PhoneВ 8 and later.
WindowsВ 8.1 and Windows ServerВ 2012В R2: This function is supported for Windows Store apps on WindowsВ 8.1, Windows ServerВ 2012В R2, and later.
WSASend function (winsock2.h)
The WSASend function sends data on a connected socket.
Syntax
Parameters
A descriptor that identifies a connected socket.
A pointer to an array of WSABUF structures. Each WSABUF structure contains a pointer to a buffer and the length, in bytes, of the buffer. For a Winsock application, once the WSASend function is called, the system owns these buffers and the application may not access them. This array must remain valid for the duration of the send operation.
The number of WSABUF structures in the lpBuffers array.
A pointer to the number, in bytes, sent by this call if the I/O operation completes immediately.
Use NULL for this parameter if the lpOverlapped parameter is not NULL to avoid potentially erroneous results. This parameter can be NULL only if the lpOverlapped parameter is not NULL.
The flags used to modify the behavior of the WSASend function call. For more information, see Using dwFlags in the Remarks section.
A pointer to a WSAOVERLAPPED structure. This parameter is ignored for nonoverlapped sockets.
A pointer to the completion routine called when the send operation has been completed. This parameter is ignored for nonoverlapped sockets.
Return value
If no error occurs and the send operation has completed immediately, WSASend returns zero. In this case, the completion routine will have already been scheduled to be called once the calling thread is in the alertable state. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError. The error code WSA_IO_PENDING indicates that the overlapped operation has been successfully initiated and that completion will be indicated at a later time. Any other error code indicates that the overlapped operation was not successfully initiated and no completion indication will occur.
Error code | Meaning |
---|---|
WSAECONNABORTED | The virtual circuit was terminated due to a time-out or other failure. |
WSAECONNRESET | For a stream socket, the virtual circuit was reset by the remote side. The application should close the socket as it is no longer usable. For a UDP datagram socket, this error would indicate that a previous send operation resulted in an ICMP «Port Unreachable» message. |
WSAEFAULT | The lpBuffers, lpNumberOfBytesSent, lpOverlapped, lpCompletionRoutine parameter is not totally contained in a valid part of the user address space. |
WSAEINTR | A blocking Windows Socket 1.1 call was canceled through WSACancelBlockingCall. |
WSAEINPROGRESS | A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function. |
WSAEINVAL | The socket has not been bound with bind or the socket is not created with the overlapped flag. |
WSAEMSGSIZE | The socket is message oriented, and the message is larger than the maximum supported by the underlying transport. |
WSAENETDOWN | The network subsystem has failed. |
WSAENETRESET | For a stream socket, the connection has been broken due to keep-alive activity detecting a failure while the operation was in progress. For a datagram socket, this error indicates that the time to live has expired. |
WSAENOBUFS | The Windows Sockets provider reports a buffer deadlock. |
WSAENOTCONN | The socket is not connected. |
WSAENOTSOCK | The descriptor is not a socket. |
WSAEOPNOTSUPP | MSG_OOB was specified, but the socket is not stream-style such as type SOCK_STREAM, OOB data is not supported in the communication domain associated with this socket, MSG_PARTIAL is not supported, or the socket is unidirectional and supports only receive operations. |
WSAESHUTDOWN | The socket has been shut down; it is not possible to WSASend on a socket after shutdown has been invoked with how set to SD_SEND or SD_BOTH. |
WSAEWOULDBLOCK | WindowsВ NT:В В Overlapped sockets: There are too many outstanding overlapped I/O requests. Nonoverlapped sockets: The socket is marked as nonblocking and the send operation cannot be completed immediately. |
WSANOTINITIALISED | A successful WSAStartup call must occur before using this function. |
WSA_IO_PENDING | An overlapped operation was successfully initiated and completion will be indicated at a later time. |
WSA_OPERATION_ABORTED | The overlapped operation has been canceled due to the closure of the socket, the execution of the «SIO_FLUSH» command in WSAIoctl, or the thread that initiated the overlapped request exited before the operation completed. For more information, see the Remarks section. |
Remarks
The WSASend function provides functionality over and above the standard send function in two important areas:
- It can be used in conjunction with overlapped sockets to perform overlapped send operations.
- It allows multiple send buffers to be specified making it applicable to the scatter/gather type of I/O.
The WSASend function is used to write outgoing data from one or more buffers on a connection-oriented socket specified by s. It can also be used, however, on connectionless sockets that have a stipulated default peer address established through the connect or WSAConnect function.
A socket created by the socket function will have the overlapped attribute as the default. A socket created by the WSASocket function with the dwFlags parameter passed to WSASocket with the WSA_FLAG_OVERLAPPED bit set will have the overlapped attribute. For sockets with the overlapped attribute, WSASend uses overlapped I/O unless both the lpOverlapped and lpCompletionRoutine parameters are NULL. In that case, the socket is treated as a non-overlapped socket. A completion indication will occur, invoking the completion of a routine or setting of an event object, when the buffer(s) have been consumed by the transport. If the operation does not complete immediately, the final completion status is retrieved through the completion routine or WSAGetOverlappedResult.
If both lpOverlapped and lpCompletionRoutine are NULL, the socket in this function will be treated as a non-overlapped socket.
For non-overlapped sockets, the last two parameters (lpOverlapped, lpCompletionRoutine) are ignored and WSASend adopts the same blocking semantics as send. Data is copied from the buffer(s) into the transport’s buffer. If the socket is non-blocking and stream-oriented, and there is not sufficient space in the transport’s buffer, WSASend will return with only part of the application’s buffers having been consumed. Given the same buffer situation and a blocking socket, WSASend will block until all of the application buffer contents have been consumed.
For message-oriented sockets, do not exceed the maximum message size of the underlying provider, which can be obtained by getting the value of socket option SO_MAX_MSG_SIZE. If the data is too long to pass atomically through the underlying protocol the error WSAEMSGSIZE is returned, and no data is transmitted.
WindowsВ Me/98/95:В В The WSASend function does not support more than 16 buffers.
Using dwFlags
The dwFlags parameter can be used to influence the behavior of the function invocation beyond the options specified for the associated socket. That is, the semantics of this function are determined by the socket options and the dwFlags parameter. The latter is constructed by using the bitwise OR operator with any of any of the values listed in the following table.
Value | Meaning |
---|---|
MSG_DONTROUTE | Specifies that the data should not be subject to routing. A Windows Sockets service provider can choose to ignore this flag. |
MSG_OOB | Send OOB data on a stream-style socket such as SOCK_STREAM only. |
MSG_PARTIAL | Specifies that lpBuffers only contains a partial message. Be aware that the error code WSAEOPNOTSUPP will be returned by transports that do not support partial message transmissions. |
В
Overlapped Socket I/O
The lpOverlapped parameter must be valid for the duration of the overlapped operation. If multiple I/O operations are simultaneously outstanding, each must reference a separate WSAOVERLAPPED structure.
If the lpCompletionRoutine parameter is NULL, the hEvent parameter of lpOverlapped is signaled when the overlapped operation completes if it contains a valid event object handle. An application can use WSAWaitForMultipleEvents or WSAGetOverlappedResult to wait or poll on the event object.
If lpCompletionRoutine is not NULL, the hEvent parameter is ignored and can be used by the application to pass context information to the completion routine. A caller that passes a non-NULLВ lpCompletionRoutine and later calls WSAGetOverlappedResult for the same overlapped I/O request may not set the fWait parameter for that invocation of WSAGetOverlappedResult to TRUE. In this case the usage of the hEvent parameter is undefined, and attempting to wait on the hEvent parameter would produce unpredictable results.
The completion routine follows the same rules as stipulated for Windows file I/O completion routines. The completion routine will not be invoked until the thread is in an alertable wait state such as can occur when the function WSAWaitForMultipleEvents with the fAlertable parameter set to TRUE is invoked.
The transport providers allow an application to invoke send and receive operations from within the context of the socket I/O completion routine, and guarantee that, for a given socket, I/O completion routines will not be nested. This permits time-sensitive data transmissions to occur entirely within a preemptive context.
The following C++ code example is a prototype of the completion routine.
The CompletionRoutine function is a placeholder for an application-defined or library-defined function name. The dwError parameter specifies the completion status for the overlapped operation as indicated by lpOverlapped. cbTransferred specifies the number of bytes sent. Currently there are no flag values defined and dwFlags will be zero. This function does not return a value.
Returning from this function allows invocation of another pending completion routine for this socket. All waiting completion routines are called before the alertable thread’s wait is satisfied with a return code of WSA_IO_COMPLETION. The completion routines can be called in any order, not necessarily in the same order the overlapped operations are completed. However, the posted buffers are guaranteed to be sent in the same order they are specified.
The order of calls made to WSASend is also the order in which the buffers are transmitted to the transport layer. WSASend should not be called on the same stream-oriented socket concurrently from different threads, because some Winsock providers may split a large send request into multiple transmissions, and this may lead to unintended data interleaving from multiple concurrent send requests on the same stream-oriented socket.
Example Code
WindowsВ PhoneВ 8: This function is supported for Windows Phone Store apps on WindowsВ PhoneВ 8 and later.
WindowsВ 8.1 and Windows ServerВ 2012В R2: This function is supported for Windows Store apps on WindowsВ 8.1, Windows ServerВ 2012В R2, and later.