Network Component  Version 7.19.0
MDK Middleware for IPv4 and IPv6 Networking
User API

BSD Socket functions and communication flow. More...

Functions

int32_t socket (int32_t family, int32_t type, int32_t protocol)
 Create a communication endpoint called socket. [thread-safe]. More...
 
int32_t bind (int32_t sock, const SOCKADDR *addr, int32_t addrlen)
 Assign a local address and port to a socket. [thread-safe]. More...
 
int32_t listen (int32_t sock, int32_t backlog)
 Set a socket in a listening mode. [thread-safe]. More...
 
int32_t accept (int32_t sock, SOCKADDR *addr, int32_t *addrlen)
 Accept connect request for a listening socket. [thread-safe]. More...
 
int32_t connect (int32_t sock, const SOCKADDR *addr, int32_t addrlen)
 Connect a socket to a remote host. [thread-safe]. More...
 
int32_t send (int32_t sock, const char *buf, int32_t len, int32_t flags)
 Send data on already connected socket. [thread-safe]. More...
 
int32_t sendto (int32_t sock, const char *buf, int32_t len, int32_t flags, const SOCKADDR *to, int32_t tolen)
 Send data to endpoint node. [thread-safe]. More...
 
int32_t sendmsg (int32_t sock, const MSGHDR *msg, int32_t flags)
 Send a message to endpoint node. [thread-safe]. More...
 
int32_t recv (int32_t sock, char *buf, int32_t len, int32_t flags)
 Receive data on already connected socket. [thread-safe]. More...
 
int32_t recvfrom (int32_t sock, char *buf, int32_t len, int32_t flags, SOCKADDR *from, int32_t *fromlen)
 Receive data from endpoint node. [thread-safe]. More...
 
int32_t recvmsg (int32_t sock, MSGHDR *msg, int32_t flags)
 Receive a message from a socket. [thread-safe]. More...
 
int32_t closesocket (int32_t sock)
 Close socket and release socket descriptor. [thread-safe]. More...
 
int32_t getpeername (int32_t sock, SOCKADDR *name, int32_t *namelen)
 Retrieve IP address and port number of the endpoint node. [thread-safe]. More...
 
int32_t getsockname (int32_t sock, SOCKADDR *name, int32_t *namelen)
 Retrieve local IP address and port number. [thread-safe]. More...
 
int32_t ioctlsocket (int32_t sock, long cmd, unsigned long *argp)
 Control IO mode of a socket. [thread-safe]. More...
 
int32_t setsockopt (int32_t sock, int32_t level, int32_t optname, const char *optval, int32_t optlen)
 Manipulate options for the socket. [thread-safe]. More...
 
int32_t getsockopt (int32_t sock, int32_t level, int32_t optname, char *optval, int32_t *optlen)
 Retrieve options for the socket. [thread-safe]. More...
 
int32_t select (int32_t 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, int32_t *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...
 
int32_t 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...
 
int32_t inet_pton (int32_t af, const char *src, void *dst)
 Convert from text address to a binary network address. [thread-safe]. More...
 
const char * inet_ntop (int32_t af, const void *src, char *dst, int32_t 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.

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) {
int32_t sock, sd, res;
char dbuf[4];
while (1) {
sock = socket (AF_INET, SOCK_STREAM, 0);
// Bind to IPv4 any address
addr.sin_port = htons(1000);
addr.sin_addr.s_addr = INADDR_ANY;
bind (sock, (SOCKADDR *)&addr, sizeof(addr));
listen (sock, 1);
sd = accept (sock, NULL, NULL);
closesocket (sock);
while (1) {
res = recv (sd, dbuf, sizeof (dbuf), 0);
if (res <= 0) {
break;
}
if (dbuf[0] == BLINKLED) {
LED_SetOut (dbuf[1]);
}
}
osDelay (100);
}
}

BSD Server Dual-Stack

Dual-Stack sockets offer the ability to create a single IPv6 socket which can handle both IPv6 and IPv4 communication. For example, a TCP listening socket for IPv6 is created, put into dual-stack mode, and bound to port 1000. The dual-stack socket can accept connections from IPv6 TCP clients and IPv4 TCP clients that connect to port 1000.

The IPv4 address is encoded in the IPv4-mapped IPv6 address with the address prefix 0:0:0:0:0:FFFF, last four bytes of the address are the IPv4 address. The IPv4 address in this format can be used in a dual-stack socket communication. If the IPv4 address is converted to a string address with the function inet_ntop, the result is represented in a hybrid dotted decimal notation. For example, the address 192.168.0.100 is converted to a string:

::FFFF:192.168.0.100

Code Example

void ServerDS_Thread (void *arg) {
int32_t sock, sd, res, on;
char dbuf[4];
while (1) {
sock = socket (AF_INET6, SOCK_STREAM, 0);
// Disable IPv6-only
on = 0;
setsockopt (sock, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&on, sizeof(on));
// Bind to IPv6 any address
addr.sin6_port = htons(1000);
addr.sin6_flowinfo = 0;
bind (sock, (SOCKADDR *)&addr, sizeof(addr));
listen (sock, 1);
sd = accept (sock, NULL, NULL);
closesocket (sock);
while (1) {
res = recv (sd, dbuf, sizeof (dbuf), 0);
if (res <= 0) {
break;
}
if (dbuf[0] == BLINKLED) {
LED_SetOut (dbuf[1]);
}
}
osDelay (100);
}
}

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) {
int32_t sock, res;
char dbuf[4];
uint8_t leds;
while (1) {
sock = socket (AF_INET, SOCK_STREAM, 0);
addr.sin_port = htons(1000);
addr.sin_addr = inet_addr ("192.168.0.100");
connect (sock, (SOCKADDR *)&addr, sizeof (addr));
leds = 0x01;
while (1) {
// Shift the LEDs
LED_SetOut (leds);
if (leds == 0x80) leds = 0x01;
else leds <<= 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 (300);
}
closesocket (sock);
}
}

Function Documentation

◆ accept()

int32_t accept ( int32_t  sock,
SOCKADDR addr,
int32_t *  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 or socket not created.
  • 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)

◆ bind()

int32_t bind ( int32_t  sock,
const SOCKADDR addr,
int32_t  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 or socket not created.
  • BSD_EINVAL = Invalid parameter 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)

◆ closesocket()

int32_t closesocket ( int32_t  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 or socket not created.
  • 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)

◆ connect()

int32_t connect ( int32_t  sock,
const SOCKADDR addr,
int32_t  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 or socket not created.
  • BSD_EINVAL = Invalid parameter or socket 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. The function behaves differently according to the type of socket:

  • SOCK_STREAM: A connection is established between the endpoints.

    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.

  • SOCK_DGRAM: 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.

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) {
int32_t sock, res, lshift;
int32_t type = (int32_t)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);
}
}

◆ gethostbyname()

HOSTENT * gethostbyname ( const char *  name,
int32_t *  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
  • To use this function, you must enable the DNS client in the selection of RTE Components.
  • 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;
int32_t 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));
}
}
osDelay (300);
}
}

◆ getpeername()

int32_t getpeername ( int32_t  sock,
SOCKADDR name,
int32_t *  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 or socket not created.
  • 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 will be 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) {
int32_t sock, sd, res, addrlen;
int32_t type = (int32_t)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);
}
}

◆ getsockname()

int32_t getsockname ( int32_t  sock,
SOCKADDR name,
int32_t *  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 or socket not created.
  • 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 will be 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) {
int32_t 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);
}
}

◆ getsockopt()

int32_t getsockopt ( int32_t  sock,
int32_t  level,
int32_t  optname,
char *  optval,
int32_t *  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_RECVDSTADDR = Receive Destination IP Address.
  • IP_TOS = Type of Service (TOS).
  • IP_TTL = Time to Live (TTL).
  • IPV6_TCLASS = Traffic Class.
  • IPV6_MULTICAST_HOPS = Multi-cast Hop Limit.
  • IPV6_RECVDSTADDR = Receive Destination IPv6 Address.
  • IPV6_V6ONLY = Restrict to IPv6 communications only.
[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 or socket not created.
  • BSD_EINVAL = Invalid parameter.
  • 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;
int32_t optlen = sizeof(optval);
getsockopt (sock, SOL_SOCKET, SO_KEEPALIVE, &optval, &optlen);
if (optval != 0) {
printf ("Keep-alive mode is active.");
}

◆ inet_addr()

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)

◆ inet_aton()

int32_t 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");

◆ inet_ntoa()

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)

◆ inet_ntop()

const char * inet_ntop ( int32_t  af,
const void *  src,
char *  dst,
int32_t  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)

◆ inet_pton()

int32_t inet_pton ( int32_t  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"

◆ ioctlsocket()

int32_t ioctlsocket ( int32_t  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 or socket not created.
  • BSD_EINVAL = Invalid parameter.
  • 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_ALIVE Sets 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 value I/O mode
0 Blocking mode
nonzero Non-blocking mode

For the command FIO_DELAY_ACK the argument values are:

*argp value Socket mode Description
0 Normal mode Waits for an ACK after each sending packet
nonzero Delay-ack mode Eliminates 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 value Socket mode Description
0 Timeout mode After a timeout a stream socket is disconnected
nonzero Keep-alive mode Stream socket sends keep alive segments on timeout to keep a connection alive

For the command FIO_FLOW_CTRL the argument values are:

*argp value Socket mode Description
0 Normal mode Stream socket dumps excess data, if the receiving buffer is full
nonzero Flow-control mode Stream 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) {
int32_t 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!");
}
..
}

◆ listen()

int32_t listen ( int32_t  sock,
int32_t  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 accepted.
Returns
status information:
  • 0 = Operation successful.
  • BSD_ESOCK = Invalid socket descriptor or socket not created.
  • 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 accepted.

This is different from the standard BSD listening function. The reason for this is that BSD sockets in the network component are just a layer on top of native TCP Socket. TCP sockets, however, are static, meaning that they are defined at compile time and are not dynamically allocated objects.

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)

◆ recv()

int32_t recv ( int32_t  sock,
char *  buf,
int32_t  len,
int32_t  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 or socket not created.
  • BSD_EINVAL = Invalid parameter.
  • 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_ECONNABORTED = Connection aborted locally.
  • 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. The excess data is treated differently according to the type of socket:

  • SOCK_STREAM: The excess data is buffered internally.

    The application can retrieve all data by multiple calls of recv function.

  • SOCK_DGRAM: The excess message data is silently discarded.

    The data is extracted from the first enqueued datagram. If the datagram or message is larger than the buffer specified, the buffer is filled with the first part of the datagram, the excess data of this datagram is silently discarded. All subsequent messages that are enqueued, are retained. The message size is currently limited to 2000 characters. You need to enable IP Fragmentation in the interface configuration so that you can receive 2000 byte datagram messages.

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.

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

The argument flags specifies the message flags:

Flag Description
MSG_DONTWAIT The 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)

◆ recvfrom()

int32_t recvfrom ( int32_t  sock,
char *  buf,
int32_t  len,
int32_t  flags,
SOCKADDR from,
int32_t *  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 or socket not created.
  • BSD_EINVAL = Invalid parameter.
  • 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_ECONNABORTED = Connection aborted locally.
  • 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. The excess data is treated differently according to the type of socket:

  • SOCK_STREAM: The excess data is buffered internally.

    The application can retrieve all data by multiple calls of recvfrom function.

  • SOCK_DGRAM: The excess message data is silently discarded.

    The data is extracted from the first enqueued datagram. If the datagram or message is larger than the buffer specified, the buffer is filled with the first part of the datagram, the excess data of this datagram is silently discarded. All subsequent messages that are enqueued, are retained. The message size is currently limited to 2000 characters. You need to enable IP Fragmentation in the interface configuration so that you can receive 2000 byte datagram messages.

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.

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

The argument flags specifies the message flags:

Flag Description
MSG_DONTWAIT The 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 will be 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) {
int32_t 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);
}
}

◆ recvmsg()

int32_t recvmsg ( int32_t  sock,
MSGHDR msg,
int32_t  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 or socket not created.
  • BSD_EINVAL = Invalid parameter.
  • 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 will be 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_DONTWAIT The 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;
int32_t 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);
}
}

◆ select()

int32_t select ( int32_t  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) {
int32_t 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);
}
}

◆ send()

int32_t send ( int32_t  sock,
const char *  buf,
int32_t  len,
int32_t  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 or socket not created.
  • BSD_EINVAL = Invalid parameter.
  • 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_EMSGSIZE = Message too large.
  • 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_DONTWAIT The 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)

◆ sendmsg()

int32_t sendmsg ( int32_t  sock,
const MSGHDR msg,
int32_t  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 or socket not created.
  • BSD_EINVAL = Invalid parameter.
  • 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_EMSGSIZE = Message too large.
  • 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);

◆ sendto()

int32_t sendto ( int32_t  sock,
const char *  buf,
int32_t  len,
int32_t  flags,
const SOCKADDR to,
int32_t  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 or socket not created.
  • BSD_EINVAL = Invalid parameter.
  • 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_EMSGSIZE = Message too large.
  • 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_DONTWAIT The 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) {
int32_t 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);
}
}

◆ setsockopt()

int32_t setsockopt ( int32_t  sock,
int32_t  level,
int32_t  optname,
const char *  optval,
int32_t  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).
  • IP_RECVDSTADDR = Receive Destination IP Address.
  • IPV6_TCLASS = Traffic Class.
  • IPV6_MULTICAST_HOPS = Multi-cast Hop Limit.
  • IPV6_RECVDSTADDR = Receive Destination IPv6 Address.
  • IPV6_V6ONLY = Restrict to IPv6 communications only.
[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 or socket not created.
  • BSD_EINVAL = Invalid parameter.
  • BSD_ENOTSUP = Option not supported for this socket type.
  • BSD_ERROR = Option failed, socket already bound.

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
int32_t timeout = 5000;
setsockopt (sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof (timeout));

◆ socket()

int32_t socket ( int32_t  family,
int32_t  type,
int32_t  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, only AF_INET and AF_INET6 address families are supported. By default, the IPv4 socket operates over the IPv4 protocol, the IPv6 socket operates over the IPv6 protocol. To convert an IPv6 socket to a dual-stack socket, the setsockopt function must be called with the IPV6_V6ONLY socket option to set this value to zero before the socket is bound to an IP address. When communicating with a dual-stack socket, the socket can operate via both, IPv4 or IPv6.

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

Type Description
SOCK_STREAM Provides 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_TCP Must be used with SOCK_STREAM socket type
IPPROTO_UDP Must 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) {
int32_t 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) {
int32_t 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);
}
}