Network Component  Version 7.10.0
MDK Middleware for IPv4 and IPv6 Networking
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
User API

BSD Socket functions and communication flow. More...

Functions

int socket (int family, int type, int protocol)
 Create a communication endpoint called socket. [thread-safe]. More...
 
int bind (int sock, const SOCKADDR *addr, int addrlen)
 Assign a local address and port to a socket. [thread-safe]. More...
 
int listen (int sock, int backlog)
 Set a socket in a listening mode. [thread-safe]. More...
 
int accept (int sock, SOCKADDR *addr, int *addrlen)
 Accept connect request for a listening socket. [thread-safe]. More...
 
int connect (int sock, const SOCKADDR *addr, int addrlen)
 Connect a socket to a remote host. [thread-safe]. More...
 
int send (int sock, const char *buf, int len, int flags)
 Send data on already connected socket. [thread-safe]. More...
 
int sendto (int sock, const char *buf, int len, int flags, const SOCKADDR *to, int tolen)
 Send data to endpoint node. [thread-safe]. More...
 
int sendmsg (int sock, const MSGHDR *msg, int flags)
 Send a message to endpoint node. [thread-safe]. More...
 
int recv (int sock, char *buf, int len, int flags)
 Receive data on already connected socket. [thread-safe]. More...
 
int recvfrom (int sock, char *buf, int len, int flags, SOCKADDR *from, int *fromlen)
 Receive data from endpoint node. [thread-safe]. More...
 
int recvmsg (int sock, MSGHDR *msg, int flags)
 Receive a message from a socket. [thread-safe]. More...
 
int closesocket (int sock)
 Close socket and release socket descriptor. [thread-safe]. More...
 
int getpeername (int sock, SOCKADDR *name, int *namelen)
 Retrieve IP address and port number of the endpoint node. [thread-safe]. More...
 
int getsockname (int sock, SOCKADDR *name, int *namelen)
 Retrieve local IP address and port number. [thread-safe]. More...
 
int ioctlsocket (int sock, long cmd, unsigned long *argp)
 Control IO mode of a socket. [thread-safe]. More...
 
int setsockopt (int sock, int level, int optname, const char *optval, int optlen)
 Manipulate options for the socket. [thread-safe]. More...
 
int getsockopt (int sock, int level, int optname, char *optval, int *optlen)
 Retrieve options for the socket. [thread-safe]. More...
 
int select (int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, struct timeval *timeout)
 Check the status of one or more sockets. [thread-safe]. More...
 
HOSTENTgethostbyname (const char *name, int *err)
 Retrieve host IP address from host name. [thread-safe]. More...
 
IN_ADDR inet_addr (const char *cp)
 Convert from text address to a network address. [thread-safe]. More...
 
int inet_aton (const char *cp, IN_ADDR *addr)
 Convert from text address to a network address. [thread-safe]. More...
 
const char * inet_ntoa (IN_ADDR in)
 Convert from network address to a text string. [not_thread-safe]. More...
 
int inet_pton (int af, const char *src, void *dst)
 Convert from text address to a binary network address. [thread-safe]. More...
 
const char * inet_ntop (int af, const void *src, char *dst, int size)
 Convert from binary network address to a text string. [thread-safe]. More...
 

Description

BSD Socket functions and communication flow.

The following table shows the available API functions for BSD sockets.

Function Description
accept Accepts a connection request queued for a listening socket.
bind Assigns a name (local address) to a socket.
closesocket Closes an existing socket and releases a socket descriptor.
connect Establishes connection between the endpoints on stream sockets.
gethostbyname Retrieves host address corresponding to a host name from a host database.
getpeername Retrieves the address of the peer to which a socket is connected.
getsockopt Retrieves options for the socket.
getsockname Retrieves the local address of the socket.
ioctlsocket Sets or retrieves some of the operating parameters on a socket.
listen Sets the socket in a listen mode.
recv Receives incoming data that has been queued for a socket.
recvfrom Receives incoming data on a datagram socket.
recvmsg Receives a message from a socket.
select Tests sockets if ready for reading, writing or have an error pending.
send Sends outgoing data on a socket.
sendto Sends outgoing data on a datagram socket to destination address.
sendmsg Sends a message to destination address.
setsockopt Manipulate options for the socket.
socket Creates a communication socket.
inet_addr Converts address from text address to a network address.
inet_aton Converts address from text address to a network address.
inet_ntoa Converts address from network address to a text string.
inet_pton Converts address from text address to a binary network address.
inet_ntop Converts address from binary network address to a text string.
Note
  • The BSD sockets implementation in the Network Component is not a complete implementation of the BSD API.
  • The BSD functions are thread safe and must be used with a CMSIS-RTOS.

Communication Flow

The image below explains the basic communication flow using BSD sockets with TCP.

NW_Diagrams.png
Flow Diagram for BSD Sockets Communication using TCP

BSD Server

The BSD server creates a socket, uses bind to attach that socket to a port, and configures it as a listening socket. This allows the server to receive incoming connection requests. Afterwards, accept is called, which will block the socket, until an incoming connection request is received. When accept returns, the SOCKADDR structure will have been filled out with the originating IP Address and port of the incoming connection. Then, accept creates a new socket, which is then used to receive data until the connection is closed by the other side.

Code Example

void Server_Thread (void *arg) {
int sock, sd, res;
int type = (int)arg;
char dbuf[4];
while (1) {
sock = socket (AF_INET, type, 0);
addr.sin_port = htons(PORT_NUM);
addr.sin_addr.s_addr = INADDR_ANY;
bind (sock, (SOCKADDR *)&addr, sizeof(addr));
if (type == SOCK_STREAM) {
listen (sock, 1);
sd = accept (sock, NULL, NULL);
closesocket (sock);
sock = sd;
}
while (1) {
res = recv (sock, dbuf, sizeof (dbuf), 0);
if (res <= 0) {
break;
}
if (dbuf[0] == BLINKLED) {
LED_SetOut (dbuf[1]);
}
}
closesocket (sock);
}
}

BSD Client

The BSD Client creates a socket calls connect, because TCP requires a negotiated connection. Afterwards, send is called to send the data to the server. Note that bind is never called, because the stack will pick a random port and an appropriate IP address. To finish the communication, the client calls closesocket.

Code Example

void Client_Thread (void *arg) {
int sock, res, lshift;
int type = (int)arg;
char dbuf[4];
uint8_t p2val;
while (1) {
sock = socket (AF_INET, type, 0);
addr.sin_port = htons(PORT_NUM);
addr.sin_addr.s_b1 = IP1;
addr.sin_addr.s_b2 = IP2;
addr.sin_addr.s_b3 = IP3;
addr.sin_addr.s_b4 = IP4;
connect (sock, (SOCKADDR *)&addr, sizeof (addr));
lshift = 1;
p2val = 0x01;
while (1) {
// Shift the LEDs
LED_SetOut (p2val);
p2val = lshift ? (p2val << 1) : (p2val >> 1);
if (p2val == 0x80) lshift = 0;
if (p2val == 0x01) lshift = 1;
// Send the data to LED Server.
dbuf[0] = BLINKLED;
dbuf[1] = p2val;
res = send (sock, (char *)&dbuf, 2, 0);
if (res < 0) {
break;
}
osDelay (100 * SPEED);
}
closesocket (sock);
}
}

Function Documentation

int accept ( int  sock,
SOCKADDR addr,
int *  addrlen 
)

Accept connect request for a listening socket. [thread-safe].

Parameters
[in]socksocket descriptor obtained with socket.
[out]addrstructure that will receive IP address and port number.
  • NULL for none.
[in,out]addrlenlength of SOCKADDR structure.
Returns
status information:
  • New socket descriptor (>0).
  • BSD_ESOCK = Invalid socket descriptor.
  • BSD_EINVAL = Socket not in listen mode.
  • BSD_ENOTSUP = Operation not supported for this socket type.
  • BSD_ELOCKED = Socket locked by another thread.
  • BSD_EWOULDBLOCK = Operation would block.
  • BSD_ECONNRESET = Connection reset by the peer.
  • BSD_ECONNABORTED = Connection aborted locally.
  • BSD_ERROR = Unspecified error.

The function accept accepts a connection request queued for a listening socket. If a connection request is pending, accept removes the request from the queue, and a new socket is created for the connection. The original listening socket remains open and continues to queue new connection requests. The socket sock must be a SOCK_STREAM type socket.

In blocking mode, which is enabled by default, this function waits for a connection request. In non blocking mode, you must call the accept function again if the error code BSD_EWOULDBLOCK is returned.

The argument sock specifies a socket descriptor returned from a previous call to socket.

The argument addr is a pointer to the SOCKADDR structure that will receive the connection node IP address and port number.

The argument addrlen is a pointer to the address length. It should initially contain the amount of space pointed to by addr. On return it contains the actual length of the address returned in bytes.

Note
  • You must call the socket function before any other function calls to the BSD socket.
  • If a negative number is returned, it represents an error code.

Code Example (see socket)

int bind ( int  sock,
const SOCKADDR addr,
int  addrlen 
)

Assign a local address and port to a socket. [thread-safe].

Parameters
[in]socksocket descriptor obtained with socket.
[in]addrstructure containing local IP address and port.
[in]addrlenlength of SOCKADDR structure.
Returns
status information:
  • 0 = Operation successful.
  • BSD_ESOCK = Invalid socket descriptor.
  • BSD_EINVAL = Invalid parameter, socket not created or already bound.
  • BSD_EADDRINUSE = Address or port already in use.
  • BSD_EISCONN = Socket already connected.

The function bind assigns a name to an unnamed socket. The name represents the local address and port of the communication endpoint.

The argument sock specifies a socket descriptor returned from a previous call to socket.

The argument addr is a pointer to the SOCKADDR structure containing the local address and port of the socket. If the port is specified as 0, the Network Core assigns a unique port from the dynamic client port range (ephemeral ports).

The argument addrlen specifies the length of the SOCKADDR structure.

Note
  • You must call the socket function before any other function calls to the BSD socket.
  • If a negative number is returned, it represents an error code.
  • You can retrieve the assigned dynamic port with getsockname function.

Code Example (see socket)

int closesocket ( int  sock)

Close socket and release socket descriptor. [thread-safe].

Parameters
[in]socksocket descriptor obtained with socket.
Returns
status information:
  • 0 = Operation successful.
  • BSD_ESOCK = Invalid socket descriptor.
  • BSD_EWOULDBLOCK = Operation would block.
  • BSD_ERROR = Unspecified error.

The function closesocket closes an existing socket and releases the socket descriptor. Further references to sock fail with BSD_EINVAL error code.

The argument sock specifies a socket descriptor returned from a previous call to socket.

In blocking mode, which is enabled by default, this function will wait until a socket is closed. In non blocking mode, you must call the closesocket function again if the error code BSD_EWOULDBLOCK is returned.

Note
  • You must call the socket function before any other function calls to the BSD socket.
  • If a negative number is returned, it represents an error code.

Code Example (see socket)

int connect ( int  sock,
const SOCKADDR addr,
int  addrlen 
)

Connect a socket to a remote host. [thread-safe].

Parameters
[in]socksocket descriptor obtained with socket.
[in]addrstructure containing remote IP address and port.
[in]addrlenlength of SOCKADDR structure.
Returns
status information:
  • 0 = Operation successful.
  • BSD_ESOCK = Invalid socket descriptor.
  • BSD_EINVAL = Invalid parameter, socket not created or in wrong state.
  • BSD_ELOCKED = Socket locked by another thread.
  • BSD_EALREADY = Connection already in progress.
  • BSD_EINPROGRESS = Operation in progress.
  • BSD_EISCONN = Socket is connected.
  • BSD_ECONNREFUSED = Connection rejected by the peer.
  • BSD_ETIMEDOUT = Operation timed out.
  • BSD_ECONNABORTED = Connection aborted locally.
  • BSD_ERROR = Unspecified error.

The function connect assigns the address of the peer communication endpoint. For SOCK_STREAM type socket, a connection is established between the endpoints. For SOCK_DGRAM type socket, an address filter is established between the endpoints. The address filter is changed with another connect function call. If the socket is not yet bound, the system implicitly binds to a random dynamic port.

In blocking mode, which is enabled by default, this function waits for a connection to be established. In non blocking mode, the function returns the error code BSD_EINPROGRESS and the connection is established asynchronously. Subsequent calls to connect for the same socket, before the connection is established, return the error code BSD_EALREADY. When the connection is established, the call to connect returns the error code BSD_EISCONN.

The argument sock specifies a socket descriptor returned from a previous call to socket.

The argument addr is a pointer to the SOCKADDR structure that contains the endpoint node IP address and port number.

The argument addrlen specifies the length of SOCKADDR structure.

Note
  • You must call the socket function before any other function calls to the BSD socket.
  • If a negative number is returned, it represents an error code.

Code Example

void Client_Thread (void *arg) {
int sock, res, lshift;
int type = (int)arg;
char dbuf[4];
uint8_t p2val;
while (1) {
sock = socket (AF_INET, type, 0);
addr.sin_port = htons(PORT_NUM);
addr.sin_addr.s_b1 = IP1;
addr.sin_addr.s_b2 = IP2;
addr.sin_addr.s_b3 = IP3;
addr.sin_addr.s_b4 = IP4;
connect (sock, (SOCKADDR *)&addr, sizeof (addr));
lshift = 1;
p2val = 0x01;
while (1) {
// Shift the LEDs
LED_SetOut (p2val);
p2val = lshift ? (p2val << 1) : (p2val >> 1);
if (p2val == 0x80) lshift = 0;
if (p2val == 0x01) lshift = 1;
// Send the data to LED Server.
dbuf[0] = BLINKLED;
dbuf[1] = p2val;
res = send (sock, (char *)&dbuf, 2, 0);
if (res < 0) {
break;
}
osDelay (100 * SPEED);
}
closesocket (sock);
}
}
HOSTENT * gethostbyname ( const char *  name,
int *  err 
)

Retrieve host IP address from host name. [thread-safe].

Parameters
[in]namehost name.
[out]errpointer to where to return error code (NULL for none):
  • 0 = Operation successful.
  • BSD_EINVAL = Invalid parameter.
  • BSD_ELOCKED = Resolver locked by another thread.
  • BSD_ETIMEDOUT = Operation timed out.
  • BSD_EHOSTNOTFOUND = Host not found.
  • BSD_ERROR = Unspecified error.
Returns
status information:
  • HOSTENT result structure.
  • NULL in case of error.

The function gethostbyname retrieves host information corresponding to a host name from a host database.

The argument name is a pointer to the null-terminated name of the host to resolve.

The argument err is a pointer to the return error code.

Note
If a negative number is returned, it represents an error code.

Code Example

static const char *hosts[] = {
"www.google.com",
"www.keil.com",
"www.microsoft.com",
"www.yahoo.com",
NULL
};
void Resolver_Thread (void *arg) {
HOSTENT *host;
IN_ADDR *addr;
int i, j, err;
for (i = 0; ; i++) {
if (hosts[i] == NULL) i = 0;
printf ("Host: %s\n",hosts[i]);
host = gethostbyname (hosts[i], &err);
if (host == NULL) {
if (err == BSD_EHOSTNOTFOUND) {
printf ("Hostname does not exist\n");
}
}
else if (host->h_addrtype == AF_INET) {
for (j = 0; host->h_addr_list[j]; j++) {
addr = (IN_ADDR *)host->h_addr_list[j];
printf("IP Address: %s\n", inet_ntoa(addr->sin_addr));
}
}
os_dly_wait (300);
}
}
int getpeername ( int  sock,
SOCKADDR name,
int *  namelen 
)

Retrieve IP address and port number of the endpoint node. [thread-safe].

Parameters
[in]socksocket descriptor obtained with socket.
[out]namestructure that will receive IP address and port number.
[in,out]namelenlength of SOCKADDR structure.
Returns
status information:
  • 0 = Operation successful.
  • BSD_ESOCK = Invalid socket descriptor.
  • BSD_EINVAL = Invalid parameter.
  • BSD_ENOTCONN = Socket not connected.

The function getpeername retrieves the address of the peer to which a socket is connected.

The argument sock specifies a socket descriptor returned from a previous call to socket.

The argument name is a pointer to the SOCKADDR structure. If name is not NULL, the remote end IP address and port number is filled in.

The argument namelen is a pointer to the address length. It should initially contain the amount of space pointed to by name. On return it contains the actual length of the address returned in bytes.

Note
  • You must call the socket function before any other function calls to the BSD socket.
  • If a negative number is returned, it represents an error code.

Code Example

void Server_Thread (void *arg) {
int sock, sd, res, addrlen;
int type = (int)arg;
char dbuf[4];
while (1) {
sock = socket (AF_INET, type, 0);
addr.sin_port = htons(PORT_NUM);
addr.sin_addr.s_addr = INADDR_ANY;
bind (sock, (SOCKADDR *)&addr, sizeof(addr));
if (type == SOCK_STREAM) {
listen (sock, 1);
sd = accept (sock, NULL, NULL);
closesocket (sock);
sock = sd;
}
while (1) {
res = recv (sock, dbuf, sizeof (dbuf), 0);
if (res <= 0) {
break;
}
procrec ((uint8_t *)dbuf);
addrlen = sizeof (addr);
getpeername (sock, (SOCKADDR *)&addr, &addrlen);
printf ("Remote IP: %s\n", inet_ntoa(addr.sin_addr));
printf ("Remote port: %d\n", ntohs (addr.sin_port));
}
closesocket (sock);
}
}
int getsockname ( int  sock,
SOCKADDR name,
int *  namelen 
)

Retrieve local IP address and port number. [thread-safe].

Parameters
[in]socksocket descriptor obtained with socket.
[out]namestructure that will receive IP address and port number.
[in,out]namelenlength of SOCKADDR structure.
Returns
status information:
  • 0 = Operation successful.
  • BSD_ESOCK = Invalid socket descriptor.
  • BSD_EINVAL = Invalid parameter or socket not bound.

The function getsockname retrieves the local address for a socket.

The argument sock specifies a socket descriptor returned from a previous call to socket.

The argument name is a pointer to the SOCKADDR structure. If name is not NULL, the local IP address and port number is filled in.

The argument namelen is a pointer to the address length. It should initially contain the amount of space pointed to by name. On return it contains the actual length of the address returned in bytes.

Note
  • You must call the socket function before any other function calls to the BSD socket.
  • If a negative number is returned, it represents an error code.

Code Example

void Server_Thread (void *arg) {
int sock, res, addrlen;
char dbuf[4];
while (1) {
addr.sin_port = htons(1001);
addr.sin_addr.s_addr = INADDR_ANY;
bind (sock, (SOCKADDR *)&addr, sizeof (addr));
addrlen = sizeof (addr);
getsockname (sock, (SOCKADDR *)&addr, &addrlen);
printf ("Local IP: %s\n", inet_ntoa(addr.sin_addr));
printf ("Local port: %d\n", ntohs (addr.sin_port));
while (1) {
res = recv (sock, dbuf, sizeof (dbuf), 0);
if (res <= 0) {
break;
}
procrec ((uint8_t *)dbuf);
}
closesocket (sock);
}
}
int getsockopt ( int  sock,
int  level,
int  optname,
char *  optval,
int *  optlen 
)

Retrieve options for the socket. [thread-safe].

Parameters
[in]socksocket descriptor obtained with socket.
[in]levellevel at which the option is defined:
  • SOL_SOCKET = Socket level.
  • IPPROTO_IP = IPv4 protocol level.
  • IPPROTO_IPV6 = IPv6 protocol level.
[in]optnamesocket option for which the value is to be retrieved:
  • SO_TYPE = Type of a socket.
  • SO_KEEPALIVE = Keep Alive.
  • SO_RCVTIMEO = Timeout for blocking receive (in ms).
  • SO_SNDTIMEO = Timeout for blocking send (in ms).
  • IP_TOS = Type of Service (TOS).
  • IP_TTL = Time to Live (TTL).
  • IPV6_TCLASS = Traffic Class.
  • IPV6_MULTICAST_HOPS = Multi-cast Hop Limit.
[out]optvalpointer to the buffer that will receive the option value.
[in,out]optleninput length of buffer, return length of the data.
Returns
status information:
  • 0 = Operation successful.
  • BSD_ESOCK = Invalid socket descriptor.
  • BSD_EINVAL = Invalid parameter or socket not created.
  • BSD_ENOTSUP = Option not supported for this socket type.

The function getsockopt retrieves options for a socket. Options may exist at multiple protocol levels.

The argument sock specifies a socket descriptor returned from a previous call to socket.

The argument level describes the level at which the option is defined (for example SOL_SOCKET).

The argument optname is the socket option for which the value is to be retrieved and must be defined within the specified level.

The argument optval points to the buffer that will receive the value of the optname.

The argument optlen contains the length of the buffer at the input and returns the length of the option information on the output.

Code Example

// Retrieve keep-alive mode for stream socket
char optval;
int optlen = sizeof(optval);
getsockopt (sock, SOL_SOCKET, SO_KEEPALIVE, &optval, &optlen);
if (optval != 0) {
printf ("Keep-alive mode is active.");
}
IN_ADDR inet_addr ( const char *  cp)

Convert from text address to a network address. [thread-safe].

Parameters
[in]cptext address in standard dotted-decimal notation.
Returns
status information:
  • Internet address on success.
  • INADDR_NONE = on error.

The function inet_addr converts the specified string to an integer value suitable for use as an Internet address.

The argument cp is a pointer to the null-terminated string in the standard IPv4 dotted decimal notation.

The function returns the converted Internet address on success, or INADDR_NONE if failed.

Code Example (see inet_aton)

int inet_aton ( const char *  cp,
IN_ADDR addr 
)

Convert from text address to a network address. [thread-safe].

Parameters
[in]cptext address in standard dotted-decimal notation.
[out]addrbuffer where the converted IPv4 address is to be stored.
Returns
status information:
  • 1 = Conversion successful.
  • 0 = Conversion failed.

The function inet_aton converts the specified string to a network address, and stores the address in the structure provided.

The argument cp is a pointer to the null-terminated string in the standard IPv4 dotted decimal notation.

The argument addr is a pointer to the buffer, where the converted address is to be stored.

The function returns 1 if the address is successfully converted, or 0 if the conversion failed.

Code Example

struct sockaddr_in sa;
const char *some_addr;
inet_aton("10.0.0.1", &sa.sin_addr); // store IP in sa
some_addr = inet_ntoa(sa.sin_addr); // return the IP
printf("%s\n", some_addr); // prints "10.0.0.1"
// This call is the same as the inet_aton() call, above:
sa.sin_addr = inet_addr("10.0.0.1");
const char * inet_ntoa ( IN_ADDR  in)

Convert from network address to a text string. [not_thread-safe].

Parameters
[in]inInternet IPv4 host address to convert.
Returns
pointer to the formatted string.

The function inet_ntoa converts the specified Internet host address to a string in the standard dotted decimal notation.

The argument in is the Internet host address to be converted.

The function returns a pointer to the null-terminated string in the standard IPv4 dotted decimal notation.

Note
The function uses a static buffer for the converted address and is therefore not thread safe.

Code Example (see inet_aton)

const char * inet_ntop ( int  af,
const void *  src,
char *  dst,
int  size 
)

Convert from binary network address to a text string. [thread-safe].

Parameters
[in]afaddress family:
  • AF_INET = Internet Address Family (IPv4).
  • AF_INET6 = Internet Address Family version 6 (IPv6).
[in]srcbinary address in network byte order to be converted.
[out]dstbuffer where the converted text address is to be stored.
[in]sizesize of the buffer, at least:
  • INET_ADDRSTRLEN for AF_INET.
  • INET6_ADDRSTRLEN for AF_INET6.
Returns
pointer to the formatted string.
  • NULL in case of error.

The function inet_ntop converts an address from network format in network byte order to presentation format.

The argument af specifies the address family. Currently, only AF_INET and AF_INET6 are supported.

The argument src is a pointer to the network address. The format of the address is interpreted according to argument af.

The argument dst is a pointer to the buffer where the converted address is to be stored.

The argument size specifies the size of the buffer pointed to by dst. The size must be at least INET_ADDRSTRLEN bytes for an IPv4 address and INET6_ADDRSTRLEN bytes for an IPv6 address.

The function returns a pointer to dst if the address is successfully converted, or NULL if the conversion failed.

Code Example (see inet_pton)

int inet_pton ( int  af,
const char *  src,
void *  dst 
)

Convert from text address to a binary network address. [thread-safe].

Parameters
[in]afaddress family:
  • AF_INET = Internet Address Family (IPv4).
  • AF_INET6 = Internet Address Family version 6 (IPv6).
[in]srctext address to be converted.
[out]dstbuffer where the converted address is to be stored.
Returns
status information:
  • 1 = Conversion successful.
  • 0 = Conversion failed.

The function inet_pton converts an address from presentation format to network format in network byte order.

The argument af specifies the address family. Currently, only AF_INET and AF_INET6 are supported.

The argument src is a pointer to the null-terminated presentation format address. The format of the address is interpreted according to argument af.

The argument dst is a pointer to the buffer where the converted address is to be stored.

The function returns 1 if the address is successfully converted, or 0 if the conversion failed.

Code Example

struct sockaddr_in sa;
char str[INET_ADDRSTRLEN];
// Store this IP address in sa
inet_pton(AF_INET, "192.168.0.100", &(sa.sin_addr));
// Now get it back and print it
inet_ntop(AF_INET, &(sa.sin_addr), str, INET_ADDRSTRLEN);
printf("%s\n", str); // prints "192.168.0.100"
int ioctlsocket ( int  sock,
long  cmd,
unsigned long *  argp 
)

Control IO mode of a socket. [thread-safe].

Parameters
[in]socksocket descriptor obtained with socket.
[in]cmdcommand to perform:
  • FIONBIO = enable non-blocking mode.
[in]argpcommand's parameter.
Returns
status information:
  • 0 = Operation successful.
  • BSD_ESOCK = Invalid socket descriptor.
  • BSD_EINVAL = Invalid parameter or socket not created.
  • BSD_ENOTSUP = Option not supported for this socket type.

The function ioctlsocket controls the I/O mode of a socket. It can be used on any socket in any state to set or retrieve some operating parameters of the socket.

The argument sock specifies a socket descriptor returned from a previous call to socket.

The argument cmd specifies a command to perform on a socket. The following commands are supported:

Command Description
FIONBIO Sets the blocking or non-blocking socket I/O mode
FIO_DELAY_ACK Sets the delay-ack or normal mode for the stream socket
FIO_KEEP_ALIVESets the keep-alive or timeout mode for the stream socket
FIO_FLOW_CTRL Sets the receive flow-control or normal mode for the stream socket

The argument argp specifies a pointer to the command's parameter.
For the command FIONBIO the argument values are:

*argp valueI/O mode
0 Blocking mode
nonzero Non-blocking mode

For the command FIO_DELAY_ACK the argument values are:

*argp valueSocket mode Description
0 Normal mode Waits for an ACK after each sending packet
nonzero Delay-ack modeEliminates the delayed acknowledge impact and improves the performance for applications sending large amount of data

For the command FIO_KEEP_ALIVE the argument values are:

*argp valueSocket mode Description
0 Timeout mode After a timeout a stream socket is disconnected
nonzero Keep-alive modeStream socket sends keep alive segments on timeout to keep a connection alive

For the command FIO_FLOW_CTRL the argument values are:

*argp valueSocket mode Description
0 Normal mode Stream socket dumps excess data, if the receiving buffer is full
nonzero Flow-control modeStream socket controls the window size and stops the transmitter, if the receiving buffer is full
Note
  • You must call the socket function before any other function calls to the BSD socket.
  • Negative return numbers represent error codes.
  • The blocking mode is enabled by default.

Code Example

void Server_Thread (void *arg) {
int sock, res;
long sck_mode;
// 0= blocking, 1= non-blocking
sck_mode = 1;
res = ioctlsocket (sock, FIONBIO, &sck_mode);
if (res == 0) {
printf ("Nonblocking mode enabled.\n");
}
else {
printf ("ioctlsocket() error\n!");
}
..
}
int listen ( int  sock,
int  backlog 
)

Set a socket in a listening mode. [thread-safe].

Parameters
[in]socksocket descriptor obtained with socket.
[in]backlognumber of connection requests that can be queued.
Returns
status information:
  • 0 = Operation successful.
  • BSD_ESOCK = Invalid socket descriptor.
  • BSD_EINVAL = Invalid parameter, socket not bound or already listening.
  • BSD_ENOTSUP = Operation not supported for this socket type.
  • BSD_ERROR = Failed to create socket backlog.

The function listen sets the specified socket to listening mode. Before calling the listen function, the bind function must be called.

The argument sock specifies a socket descriptor returned from a previous call to socket.

The argument backlog specifies a maximum number of connection requests that can be queued.

Note
  • You must call the socket function before any other function calls to the BSD socket.
  • If a negative number is returned, it represents an error code.

Code Example (see socket)

int recv ( int  sock,
char *  buf,
int  len,
int  flags 
)

Receive data on already connected socket. [thread-safe].

Parameters
[in]socksocket descriptor obtained with socket.
[out]bufpointer to application data buffer to store the data to.
[in]lensize of application data buffer (in bytes).
[in]flagsmessage flags:
  • MSG_DONTWAIT = don't wait for data.
  • MSG_PEEK = peek at incoming data.
  • 0 = for none.
Returns
status information:
  • Number of bytes received (>0).
  • BSD_ESOCK = Invalid socket descriptor.
  • BSD_EINVAL = Invalid parameter or socket not created.
  • BSD_ELOCKED = Socket locked by another thread.
  • BSD_ENOTCONN = Socket not connected.
  • BSD_ECONNRESET = Connection reset by the peer.
  • BSD_EWOULDBLOCK = Operation would block.
  • BSD_ETIMEDOUT = Operation timed out.
  • BSD_ERROR = Unspecified error.

The function recv receives incoming data that has been queued for the socket. This function can be used with both SOCK_STREAM and SOCK_DGRAM type sockets. It reads as much information as currently available up to the size of the buffer specified.

In blocking mode, which is enabled by default, this function waits for received data. In non blocking mode, you must call the recv function again if the error code BSD_EWOULDBLOCK is returned.

The argument sock specifies a socket descriptor returned from a previous call to socket.

The argument buf is a pointer to the application data buffer for storing the data to. If the available data is too large to fit in the supplied application buffer buf, excess bytes are discarded in case of SOCK_DGRAM sockets. For socket types SOCK_STREAM, the data is buffered internally so the application can retrieve all data by multiple calls of recv function.

The argument len specifies the size of the application data buffer. The argument flags specifies the message flags:

Flag Description
MSG_DONTWAITThe function returns with error code BSD_EWOULDBLOCK or number of bytes received instead of blocking the socket.
MSG_PEEK The function peeks at incoming data. The data is copied into the buffer, but is not removed from the input queue.
Note
  • You must call the socket function before any other function calls to the BSD socket.
  • If a negative number is returned, it represents an error code.

Code Example (see socket)

int recvfrom ( int  sock,
char *  buf,
int  len,
int  flags,
SOCKADDR from,
int *  fromlen 
)

Receive data from endpoint node. [thread-safe].

Parameters
[in]socksocket descriptor obtained with socket.
[out]bufpointer to application data buffer to store the data to.
[in]lensize of application data buffer (in bytes).
[in]flagsmessage flags:
  • MSG_DONTWAIT = don't wait for data.
  • MSG_PEEK = peek at incoming data.
  • 0 = for none.
[out]fromstructure that will receive IP address and port number.
  • NULL for none.
[in,out]fromlenlength of SOCKADDR structure.
Returns
status information:
  • Number of bytes received (>0).
  • BSD_ESOCK = Invalid socket descriptor.
  • BSD_EINVAL = Invalid parameter or socket not created.
  • BSD_ELOCKED = Socket locked by another thread.
  • BSD_ENOTCONN = Socket not connected.
  • BSD_ECONNRESET = Connection reset by the peer.
  • BSD_EWOULDBLOCK = Operation would block.
  • BSD_ETIMEDOUT = Operation timed out.
  • BSD_ERROR = Unspecified error.

The function recvfrom is used to receive data that has been queued for a socket. It is normally used to receive messages on SOCK_DGRAM socket type, but can also be used to receive a reliable, ordered stream of data on a connected SOCK_STREAM socket type. It reads as much information as currently available up to the size of the buffer specified.

In blocking mode, which is enabled by default, this function waits for received data. In non blocking mode, you must call the recvfrom function again if the error code BSD_EWOULDBLOCK is returned.

The argument sock specifies a socket descriptor returned from a previous call to socket.

The argument buf is a pointer to the application data buffer for storing the data to. If the available data is too large to fit in the supplied application buffer buf, excess bytes are discarded in case of SOCK_DGRAM sockets. For socket types SOCK_STREAM, the data is buffered internally so the application can retrieve all data by multiple calls of recvfrom function.

The argument len specifies the size of the application data buffer.

The argument flags specifies the message flags:

Flag Description
MSG_DONTWAITThe function returns with error code BSD_EWOULDBLOCK or number of bytes received instead of blocking the socket.
MSG_PEEK The function peeks at incoming data. The data is copied into the buffer, but is not removed from the input queue.

The argument from is a pointer to the SOCKADDR structure. If from is not NULL, the source IP address and port number of the datagram is filled in.

The argument fromlen is a pointer to the address length. It should initially contain the amount of space pointed to by from. On return it contains the actual length of the address returned in bytes.

If the socket type is SOCK_STREAM, arguments from and fromlen are ignored.

Note
  • You must call the socket function before any other function calls to the BSD socket.
  • If a negative number is returned, it represents an error code.
  • The number of bytes actually read can be less than len.

Code Example

void Server_Thread (void *arg) {
int sock, res, addrlen;
char dbuf[4];
while (1) {
sock = socket (AF_INET, SOCK_DGRAM, 0);
addr.sin_port = htons(PORT_NUM);
addr.sin_addr.s_addr = INADDR_ANY;
bind (sock, (SOCKADDR *)&addr, sizeof(addr));
while (1) {
addrlen = sizeof (addr);
res = recvfrom (sock, dbuf, sizeof (dbuf), 0, (SOCKADDR *)&addr, &addrlen);
if (res <= 0) {
break;
}
procrec ((uint8_t *)dbuf);
printf ("Remote IP: %s\n", inet_ntoa(addr.sin_addr));
printf ("Remote port: %d\n", ntohs (addr.sin_port));
}
closesocket (sock);
}
}
int recvmsg ( int  sock,
MSGHDR msg,
int  flags 
)

Receive a message from a socket. [thread-safe].

Parameters
[in]socksocket descriptor obtained with socket.
[in,out]msgpointer to MSGHDR structure containing:
  • pointer to buffer to store the source address to (NULL for none).
  • array of application buffer(s) for the incomming message.
  • pointer to buffer for the ancillary data (NULL for none).
[in]flagsmessage flags:
  • MSG_DONTWAIT = don't wait for data.
  • MSG_PEEK = peek at incoming data.
  • 0 = for none.
Returns
status information:
  • Number of bytes received (>0).
  • BSD_ESOCK = Invalid socket descriptor.
  • BSD_EINVAL = Invalid parameter or socket not created.
  • BSD_ELOCKED = Socket locked by another thread.
  • BSD_ENOTSUP = Operation not supported.
  • BSD_ENOTCONN = Socket not connected.
  • BSD_EWOULDBLOCK = Operation would block.
  • BSD_ETIMEDOUT = Operation timed out.
  • BSD_ECONNABORTED = Connection aborted locally.
  • BSD_ERROR = Unspecified error.

The function recvmsg is used to receive a message from a SOCK_STREAM or SOCK_DGRAM socket. It is normally used with SOCK_DGRAM sockets because it permits the application to retrieve the source address of received data.

In blocking mode, which is enabled by default, this function waits for received data. In non blocking mode, you must call the recvmsg function again if the error code BSD_EWOULDBLOCK is returned.

The argument sock specifies a socket descriptor returned from a previous call to socket.

The argument msg is a pointer to the msghdr structure, containing both the buffer to store the source address and the buffers for the incoming message.

  • The msg_name member is a pointer to the SOCKADDR structure. If msg_name is not NULL, the source IP address and port number of the datagram is filled in.
  • The msg_namelen member is the address length. It should initially contain the amount of space pointed to by msg_name. On return it contains the actual length of the address returned in bytes.
  • The msg_iov member is a pointer to scatter/gatther array of type IOVEC. This array can specify one or more buffers, where the received data shall be stored.
  • The msg_iovlen member contains the number of IOVEC buffers, that are available in the IOVEC array.
  • The msg_control member is a pointer to a buffer, that will receive ancillary data.
  • The msg_controllen member is the buffer length. It should initially contain the amount of space pointed to by msg_control. On return it contains the actual length of the control data returned in bytes. The control data can be processed with the following macros:
Macro name Description
CMSG_FIRSTHDR(mhdr) Returns a pointer to the first CMSGHDR structure in the mhdr.
CMSG_NXTHDR(mhdr,cmsg)Returns a pointer to the CMSGHDR structure describing the next ancillary data object.
CMSG_DATA(cmsg) Returns a pointer to the data of ancillary data object.
CMSG_ALIGN(len) Rounds the argument up to the next even multiple of 4 bytes.
CMSG_LEN(len) Gives the length of an ancillary data object without padding.
CMSG_SPACE(len) Gives the length of an ancillary data object including the padding needed.
  • The msg_flags member is ignored on input, but may contain meaningful values on output:
Flag Description
MSG_TRUNC Normal data was truncated, excess bytes are discarded in case of SOCK_DGRAM sockets.
MSG_CTRUNC Control data was truncated, ancillary data buffer is too small.

The argument flags specifies the message flags:

Flag Description
MSG_DONTWAITThe function returns with error code BSD_EWOULDBLOCK or number of bytes received instead of blocking the socket.
MSG_PEEK The function peeks at incoming data. The data is copied into the buffer, but is not removed from the input queue.
Note
  • You must call the socket function before any other function calls to the BSD socket.
  • If a negative number is returned, it represents an error code.

Code Example

void Server_Thread (void *arg) {
IN_ADDR dst_ip;
MSGHDR msg;
IOVEC iov;
union {
CMSGHDR cm;
uint8_t raw[32];
} control_un;
CMSGHDR *cmsg;
int sock, res;
char dbuf[4];
char enable;
while (1) {
sock = socket (AF_INET, SOCK_DGRAM, 0);
addr.sin_port = htons(PORT_NUM);
addr.sin_addr.s_addr = INADDR_ANY;
bind (sock, (SOCKADDR *)&addr, sizeof(addr));
// Enable receiving destination IPv4 address
enable = 1;
setsockopt (sock, IPPROTO_IP, IP_RECVDSTADDR, &enable, sizeof(enable));
// Specify receive IO buffer
iov.iov_base = &dbuf[0];
iov.iov_len = sizeof(dbuf);
// Construct message header
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_name = &addr;
msg.msg_namelen = sizeof(addr);
msg.msg_control = &control_un.cm;
msg.msg_controllen = sizeof(control_un);
while (1) {
res = recvmsg (sock, &msg, 0);
if (res <= 0) {
break;
}
// Process control data
for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
if (cmsg->cmsg_level == IPPROTO_IP && cmsg->cmsg_type == IP_RECVDSTADDR) {
IN_ADDR *pia = (IN_ADDR *)CMSG_DATA(cmsg);
dst_ip.sin_addr.s_addr = pia->s_addr;
}
}
// Process normal data
procrec ((uint8_t *)dbuf);
printf ("Remote IP: %s\n", inet_ntoa(addr.sin_addr));
printf ("Remote port: %d\n", ntohs (addr.sin_port));
}
closesocket (sock);
}
}
int select ( int  nfds,
fd_set readfds,
fd_set writefds,
fd_set errorfds,
struct timeval timeout 
)

Check the status of one or more sockets. [thread-safe].

Parameters
[in]nfdsrange of sockets to be checked.
[in,out]readfdspointer to the set of sockets to check for read.
  • NULL for none.
[in,out]writefdspointer to the set of sockets to check for write.
  • NULL for none.
[in,out]errorfdspointer to the set of sockets to check for error.
  • NULL for none.
[in]timeoutpointer to maximum time for select to wait.
  • NULL for blocking wait for event.
Returns
status information:
  • number of ready sockets (>0)
  • 0 = Operation timed out.
  • BSD_EINVAL = Invalid parameter.
  • BSD_ERROR = Suspend operation failed.

The function select indicates which of the specified sockets is ready for reading, ready for writing, or has an error condition pending. If the specified condition is false for all of the specified sockets, select blocks, up to the specified timeout interval, until the specified condition is true for at least one of the specified sockets.

The argument nfds specifies the range of sockets to be tested. The select function tests sockets in the range of 0 to nfds-1.

The argument readfds specifies the set of sockets to be checked for being ready to read on input, and on output indicates which sockets are ready to read. If the value of readfds is NULL, the sockets are not checked for being ready to read.

The argument writefds specifies the set of sockets to be checked for being ready to write on input, and on output indicates which sockets are ready to write. If the value of writefds is NULL, the sockets are not checked for being ready to write.

The argument errorfds specifies the set of sockets to be checked for error conditions pending on input, and on output indicates which sockets have error condition pending. If the value of errorfds is NULL, the sockets are not checked for error condition pending.

On exit, each set of sockets is modified in place to indicate which sockets actually changed status. Thus, if using select within a loop, the sets must be reinitialized before each call.

The argument timeout specifies a maximum interval to wait for the selection to complete. If the value of timeout is NULL, the select function blocks until an event occurs. If both members of the timeout structure are 0, select function does not block.

The set of sockets of type fd_set can be initialized and tested with the following macros:

Macro name Description
FD_SET(fd, set) Sets the bit for the socket fd in the set of sockets specified with set.
FD_CLR(fd, set) Clears the bit for the socket fd in the set of sockets specified with set.
FD_ISSET(fd, set)Returns a nonzero value if the bit for the socket fd is set in the set of sockets specified with set, and 0 otherwise.
FD_ZERO(set) Initialises the set of sockets set to have zero bits for all socket descriptors.
Note
  • If a negative number is returned, it represents an error code.

Code Example

void Server_Thread (void *arg) {
int sock, sd, res, addrlen;
struct fd_set read_fds;
char dbuf[4];
while (1) {
sock = socket (AF_INET, SOCK_STREAM, 0);
addr.sin_port = htons(PORT_NUM);
addr.sin_addr.s_addr = INADDR_ANY;
bind (sock, (SOCKADDR *)&addr, sizeof(addr));
listen (sock, 1);
sd = accept (sock, NULL, NULL);
closesocket (sock);
sock = sd;
while (1) {
FD_ZERO (&read_fds);
FD_SET (sock, &read_fds);
res = select (sock+1, &read_fds, NULL, NULL, NULL);
if (res <= 0) {
break;
}
if (FD_ISSET (sock, &read_fds) {
// Data is ready, recv will not block
res = recv (sock, dbuf, sizeof (dbuf), 0);
if (res <= 0) {
break;
}
procrec ((uint8_t *)dbuf);
}
}
closesocket (sock);
}
}
int send ( int  sock,
const char *  buf,
int  len,
int  flags 
)

Send data on already connected socket. [thread-safe].

Parameters
[in]socksocket descriptor obtained with socket.
[in]bufpointer to application data buffer to transmit.
[in]lenlength of data (in bytes).
[in]flagsmessage flags:
  • MSG_DONTWAIT = don't wait to send data.
  • 0 = for none.
Returns
status information:
  • Number of bytes sent (>0).
  • BSD_ESOCK = Invalid socket descriptor.
  • BSD_EINVAL = Invalid parameter or socket not created.
  • BSD_ELOCKED = Socket locked by another thread.
  • BSD_ENOTCONN = Socket not connected.
  • BSD_ECONNRESET = Connection reset by the peer.
  • BSD_EWOULDBLOCK = Operation would block.
  • BSD_ETIMEDOUT = Operation timed out.
  • BSD_EDESTADDRREQ = Destination address required.
  • BSD_ECONNABORTED = Connection aborted locally.
  • BSD_ENOMEM = Not enough memory.
  • BSD_ERROR = Unspecified error.

The function send is used to send data on an already connected socket. This function is normally used to send a reliable, ordered stream of data bytes on a SOCK_STREAM socket type. It can also be used to send datagrams on a SOCK_DGRAM socket types.

The argument sock specifies a socket descriptor returned from a previous call to socket.

The argument buf is a pointer to the application data buffer containing data to transmit. The buffer data length is not limited in size. If the data length is too large for one packet, the send function will fragment the data and send it in several successive data packets:

  • In blocking mode, which is enabled by default, this function returns after the data has been successfully queued for transmission.
  • In non blocking mode, the function returns immediately without blocking the system.

The argument len specifies the length of data in bytes. The argument flags specifies the message flags:

Flag Description
MSG_DONTWAITThe function returns with error code BSD_EWOULDBLOCK or number of bytes sent instead of blocking the socket

Return value, when positive, represents the number of bytes sent, which can be less than len.

Note
  • You must call the socket function before any other function calls to the BSD socket.
  • If a negative number is returned, it represents locally detected error code.

Code Example (see connect)

int sendmsg ( int  sock,
const MSGHDR msg,
int  flags 
)

Send a message to endpoint node. [thread-safe].

Parameters
[in]socksocket descriptor obtained with socket.
[in]msgpointer to MSGHDR structure containing:
  • pointer to target address (NULL for none).
  • array of application buffer(s) containing the message.
  • pointer to the ancillary data (NULL for none).
[in]flagsmessage flags:
  • 0 = for none.
Returns
status information:
  • Number of bytes sent (>0).
  • BSD_ESOCK = Invalid socket descriptor.
  • BSD_EINVAL = Invalid parameter or socket not created.
  • BSD_ELOCKED = Socket locked by another thread.
  • BSD_ENOTSUP = Operation not supported.
  • BSD_EDESTADDRREQ = Destination address required.
  • BSD_EWOULDBLOCK = Operation would block.
  • BSD_ECONNABORTED = Connection aborted locally.
  • BSD_ENOMEM = Not enough memory.
  • BSD_ERROR = Unspecified error.

The function sendmsg is used to send a message from a SOCK_STREAM or SOCK_DGRAM socket. It is normally used with SOCK_DGRAM sockets because it permits the application to specify the destination address where the message is to be sent to.

The argument sock specifies a socket descriptor returned from a previous call to socket.

The argument msg is a pointer to the msghdr structure, containing both the destination address and the buffers for the outgoing message.

  • The msg_name member is a pointer to the SOCKADDR structure that contains the IP address and port number of the endpoint node. If msg_name is NULL, the destination address specified with a call to connect function is used.
  • The msg_namelen member is the address length in bytes.
  • The msg_iov member is a pointer to scatter/gatther array of type IOVEC. This array can specify one or more buffers, containing the data to be sent.
  • The msg_iovlen member contains the number of IOVEC buffers, that are available in the IOVEC array.
  • The msg_control member is a pointer to a buffer, that contains the ancillary data.
  • The msg_controllen member is the ancillary data length.
  • The msg_flags member is ignored.

The argument flags specifies the message flags.

Note
  • You must call the socket function before any other function calls to the BSD socket.
  • If a negative number is returned, it represents an error code.

Code Example

char msg1[] = { "Message part 1" };
char msg2[] = { "Message part 2" };
char msg3[] = { "Message part 3" };
MSGHDR msg;
IOVEC iov[3];
sock = socket (AF_INET, SOCK_DGRAM, 0);
// Specify destination address
addr.sin_port = htons(1025);
addr.sin_addr = inet_addr("10.0.0.1");
// Specify message buffers
iov[0].iov_base = &msg1;
iov[0].iov_len = strlen(msg1);
iov[1].iov_base = &msg2;
iov[1].iov_len = strlen(msg2);
iov[2].iov_base = &msg3;
iov[2].iov_len = strlen(msg3);
// Construct message header
msg.msg_iov = &iov[0];
msg.msg_iovlen = 3;
msg.msg_name = &addr;
msg.msg_namelen = sizeof(addr);
msg.msg_control = NULL;
msg.msg_controllen = 0;
res = sendmsg (sock, &msg, 0);
if (res <= 0) {
// Error
}
closesocket (sock);
int sendto ( int  sock,
const char *  buf,
int  len,
int  flags,
const SOCKADDR to,
int  tolen 
)

Send data to endpoint node. [thread-safe].

Parameters
[in]socksocket descriptor obtained with socket.
[in]bufpointer to application data buffer to transmit.
[in]lenlength of data (in bytes).
[in]flagsmessage flags:
  • MSG_DONTWAIT = don't wait to send data.
  • 0 = for none.
[in]tostructure containing remote IP address and port.
[in]tolenlength of SOCKADDR structure.
Returns
status information:
  • Number of bytes sent (>0).
  • BSD_ESOCK = Invalid socket descriptor.
  • BSD_EINVAL = Invalid parameter or socket not created.
  • BSD_ELOCKED = Socket locked by another thread.
  • BSD_ENOTCONN = Socket not connected.
  • BSD_ECONNRESET = Connection reset by the peer.
  • BSD_EWOULDBLOCK = Operation would block.
  • BSD_ETIMEDOUT = Operation timed out.
  • BSD_EDESTADDRREQ = Destination address required.
  • BSD_ECONNABORTED = Connection aborted locally.
  • BSD_ENOMEM = Not enough memory.
  • BSD_ERROR = Unspecified error.

The function sendto is used to send data. It is normally used to send messages on a SOCK_DGRAM socket type, but can also be used to send data on a connected SOCK_STREAM socket type.

If the socket type is SOCK_DGRAM and the socket is not yet bound, the system implicitly binds to a random dynamic port.

The argument sock specifies a socket descriptor returned from a previous call to socket.

The argument buf is a pointer to the application data buffer containing data to transmit. The buffer data length is not limited in size. If the data length is too large for one packet, the sendto function will fragment the data and send it in several successive data packets:

  • In blocking mode, which is enabled by default, this function returns after the data has been successfully queued for transmission.
  • In non blocking mode, the function returns immediately without blocking the system.

The argument len specifies the length of data in bytes. The argument flags specifies the message flags:

Flag Description
MSG_DONTWAITThe function returns with error code BSD_EWOULDBLOCK or number of bytes sent instead of blocking the socket

The argument to is a pointer to the SOCKADDR structure that contains the endpoint node IP address and port number.

The argument tolen specifies the length of SOCKADDR structure.

If the socket type is SOCK_STREAM, arguments to and tolen are ignored.

Return value, when positive, represents the number of bytes sent, which can be less than len.

Note
  • You must call the socket function before any other function calls to the BSD socket.
  • If a negative number is returned, it represents locally detected error code.

Code Example

void Client_Thread (void *arg) {
int sock, res, lshift;
char dbuf[4];
uint8_t p2val;
while (1) {
sock = socket (AF_INET, SOCK_DGRAM, 0);
addr.sin_port = htons(PORT_NUM);
addr.sin_addr.s_b1 = IP1;
addr.sin_addr.s_b2 = IP2;
addr.sin_addr.s_b3 = IP3;
addr.sin_addr.s_b4 = IP4;
lshift = 1;
p2val = 0x01;
while (1) {
// Shift the LEDs
LED_SetOut (p2val);
p2val = lshift ? (p2val << 1) : (p2val >> 1);
if (p2val == 0x80) lshift = 0;
if (p2val == 0x01) lshift = 1;
// Send the data to LED Server.
dbuf[0] = BLINKLED;
dbuf[1] = p2val;
res = sendto (sock, (char *)&dbuf, 2, 0, (SOCKADDR *)&addr, sizeof (addr));
if (res < 0) {
break;
}
osDelay (100 * SPEED);
}
closesocket (sock);
}
}
int setsockopt ( int  sock,
int  level,
int  optname,
const char *  optval,
int  optlen 
)

Manipulate options for the socket. [thread-safe].

Parameters
[in]socksocket descriptor obtained with socket.
[in]levellevel at which the option is defined:
  • SOL_SOCKET = Socket level.
  • IPPROTO_IP = IPv4 protocol level.
  • IPPROTO_IPV6 = IPv6 protocol level.
[in]optnamesocket option for which the value is to be set:
  • SO_KEEPALIVE = Keep Alive.
  • SO_RCVTIMEO = Timeout for blocking receive (in ms).
  • SO_SNDTIMEO = Timeout for blocking send (in ms).
  • IP_TOS = Type of Service (TOS).
  • IP_TTL = Time to Live (TTL).
  • IPV6_TCLASS = Traffic Class.
  • IPV6_MULTICAST_HOPS = Multi-cast Hop Limit.
[in]optvalpointer to the buffer containing the option value.
[in]optlensize of the buffer containing the option value.
Returns
status information:
  • 0 = Operation successful.
  • BSD_ESOCK = Invalid socket descriptor.
  • BSD_EINVAL = Invalid parameter or socket not created.
  • BSD_ENOTSUP = Option not supported for this socket type.

The function setsockopt sets options for a socket. Options may exist at multiple protocol levels.

The argument sock specifies a socket descriptor returned from a previous call to socket.

The argument level describes the level at which the option is defined (for example SOL_SOCKET).

The argument optname is the socket option for which the value is to be set. The optname argument must be a socket option defined within the specified level.

The argument optval points to the buffer containing the value of the optname.

The argument optlen tells the exact length of the option.

Code Example

// Timeout 5 sec
int timeout = 5000;
setsockopt (sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof (timeout));
int socket ( int  family,
int  type,
int  protocol 
)

Create a communication endpoint called socket. [thread-safe].

Parameters
[in]familyaddress family:
  • AF_INET = address family IPv4.
  • AF_INET6 = address family IPv6.
[in]typeconnection type of a socket:
  • SOCK_STREAM = connection based type.
  • SOCK_DGRAM = datagram connectionless type.
[in]protocolprotocol type:
  • IPPROTO_TCP = must be used with SOCK_STREAM type.
  • IPPROTO_UDP = must be used with SOCK_DGRAM TYPE.
  • 0 = for system auto-select.
Returns
status information:
  • Socket descriptor (>0).
  • BSD_EINVAL = Invalid parameter.
  • BSD_ENOMEM = No free sockets available.

The function socket creates a communication endpoint called a socket.

The argument family specifies the address family. Currently the only acceptable value is AF_INET.

The argument type specifies the communication semantics. The following are the currently supported types:

Type Description
SOCK_STREAMProvides a reliable connection based data stream that is full-duplex
SOCK_DGRAM Provides connectionless communication that is unreliable

The argument protocol specifies the protocol that must be used with socket type:

Protocol Description
IPPROTO_TCPMust be used with SOCK_STREAM socket type
IPPROTO_UDPMust be used with SOCK_DGRAM socket type
0 The system selects a matching protocol for the socket type
Note
  • You must call the socket function before any other function calls to the BSD socket.
  • If a negative number is returned, it represents an error code.

Code Example (Stream Socket)

void Server_Thread (void *arg) {
int sock, sd, res;
char dbuf[4];
while (1) {
sock = socket (AF_INET, SOCK_STREAM, 0);
addr.sin_port = htons(PORT_NUM);
addr.sin_addr.s_addr = INADDR_ANY;
bind (sock, (SOCKADDR *)&addr, sizeof(addr));
listen (sock, 1);
sd = accept (sock, NULL, NULL);
closesocket (sock);
sock = sd;
while (1) {
res = recv (sock, dbuf, sizeof (dbuf), 0);
if (res <= 0) {
break;
}
if (dbuf[0] == BLINKLED) {
LED_SetOut (dbuf[1]);
}
}
closesocket (sock);
}
}

Code Example (Datagram Socket)

void Server_Thread (void *arg) {
int sock, res;
char dbuf[4];
while (1) {
sock = socket (AF_INET, SOCK_DGRAM, 0);
addr.sin_port = htons(PORT_NUM);
addr.sin_addr.s_addr = INADDR_ANY;
bind (sock, (SOCKADDR *)&addr, sizeof(addr));
while (1) {
res = recv (sock, dbuf, sizeof (dbuf), 0);
if (res <= 0) {
break;
}
if (dbuf[0] == BLINKLED) {
LED_SetOut (dbuf[1]);
}
}
closesocket (sock);
}
}