send()

PROTOTYPE

#include <sockets.h>

ssize_t send(int socket, const void *buffer, size_t length, int flags);

DESCRIPTION

send() writes data to the connected socket specified by socket. buffer points where the data is copied from. length is the number of bytes to write. flags is 0 or a bitwise OR of the following symbols that modify send()’s behavior:

  • MSG_DONTROUTE: Temporarily sets the SO_DONTROUTE socket option.
  • MSG_DONTWAIT: Temporarily makes the socket non-blocking (TCP only).
  • MSG_OOB: Marks last byte as urgent and sends urgent notification to peer (TCP only).

For TCP sockets, send() attempts to copy length number of bytes to the socket’s send buffer. If the buffer is full and the socket is blocking (the default), send() blocks until space is freed or the send timeout expires. If the socket is non-blocking and the send buffer is full, send() sets errno to EWOULDBLOCK and returns -1 immediately.

A socket is made non-blocking using the ioctlsocket() FIONBIO option or (temporarily) the MSG_DONTWAIT flag. The default send wait is forever but other values can be set using the setsockopt() SO_SNDTIMEO option.

UDP data is transferred as datagrams; one per send(). The maximum length is NET_BIG_SIZE (defined in “tcp_ip.h”) minus the UDP header size (8 bytes), IP header size (20 bytes), and NI header space (16 bytes). If length exceeds this limit, send() sets errno to EMSGSIZE and returns -1. If no send buffer is available, send() sets errno to ENOBUFS and returns -1. A UDP send() call never blocks.

If successful, send() returns the number of bytes sent. Otherwise, it sets errno and returns -1.

ERROR CODES

ECONNABORTED Connection was aborted because of unacknowledged transmissions.
ECONNRESET Connection was forcibly closed by remote host (received RST).
EFAULT buffer is NULL and length is not 0.
EHOSTUNREACH Timed out after receiving a “host unreachable” ICMP message.
EMFILE Socket not bound to local port number and no port is free (UDP only).
EMSGSIZE length is larger than max datagram size (UDP only).
ENETDOWN TargetTCP has not been initialized.
ENETUNREACH No route exists to destination network (UDP only).
ENOBUFS No buffer space available for UDP datagram or TCP urgent data.
ENOTCONN The socket is not connected.
ENOTSOCK socket is not a valid socket handle.
EOPNOTSUPP MSG_OOB specified on UDP socket.
ESHUTDOWN The socket has been shutdown for sending by shutdown().
ETIMEDOUT Connection dropped because of no response from peer (TCP only).
EWOULDBLOCK Socket is non-blocking and send buffer is full (TCP only).

EXAMPLE

  /*-------------------------------------------------------------------*/
  /* Send FTP get command to server.                                   */
  /*-------------------------------------------------------------------*/
  rc = send(sock, send_buf, strlen(send_buf), 0);
  if (rc < 0)
    error("send() failed");