Sunteți pe pagina 1din 69



CycloneTCP User Manual

© 2010 - 2019 Oryx Embedded Version 1.9.2


CycloneTCP User Manual

Contents
1 Overview ....................................................................................................................... 4
1.1 CycloneTCP Features ............................................................................................. 4
1.2 TCP/IP Basics ......................................................................................................... 5
1.3 Socket Programming ............................................................................................... 6
1.4 Task Model ............................................................................................................. 7
1.5 Memory Management ............................................................................................. 8
1.5.1 Dynamic allocation ........................................................................................... 8
1.5.2 Memory pool .................................................................................................... 8
2 Using the stack .............................................................................................................. 9
2.1 Source files ............................................................................................................. 9
2.2 Project properties .................................................................................................... 9
2.3 RTOS configuration ................................................................................................10
2.4 Ethernet drivers ......................................................................................................11
2.4.1 Ethernet MAC drivers ......................................................................................11
2.4.2 Ethernet PHY drivers.......................................................................................12
2.4.3 Standalone Ethernet controllers ......................................................................12
2.5 TCP/IP stack initialization .......................................................................................13
3 Stack Configuration ......................................................................................................14
3.1 TCP/IP stack configuration .....................................................................................14
3.2 Memory pool configuration .....................................................................................15
3.3 IPv4 configuration ..................................................................................................15
3.4 ARP configuration ..................................................................................................16
3.5 IGMP configuration ................................................................................................16
3.6 Auto-IP configuration ..............................................................................................16
3.7 IPv6 configuration ..................................................................................................16
3.8 NDP configuration ..................................................................................................17
3.9 MLD configuration ..................................................................................................17
3.10 SLAAC configuration ..........................................................................................17
3.11 TCP configuration ...............................................................................................17
3.12 UDP configuration...............................................................................................18
3.13 Socket configuration ...........................................................................................19
3.14 Raw socket configuration ....................................................................................19
3.15 DNS cache configuration ....................................................................................20
3.16 DNS client configuration .....................................................................................20
3.17 mDNS client configuration ..................................................................................20
3.18 mDNS responder configuration ...........................................................................20
3.19 NetBIOS NS client configuration .........................................................................21
3.20 NetBIOS NS responder configuration .................................................................21
3.21 DNS-SD configuration ........................................................................................21
4 Function reference ........................................................................................................22
4.1 TCP/IP Stack Configuration....................................................................................22
4.1.1 netInit ..............................................................................................................22
4.1.2 netConfigInterface ...........................................................................................23
4.1.3 netSetInterfaceName ......................................................................................24
4.1.4 netSetDriver ....................................................................................................25
4.1.5 netSetPhyDriver ..............................................................................................26
4.1.6 netSetMacAddr ...............................................................................................27
4.2 IPv4 manual configuration ......................................................................................28
4.2.1 ipv4SetHostAddr .............................................................................................28
4.2.2 ipv4SetSubnetMask ........................................................................................29

2 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

4.2.3 ipv4SetDefaultGateway ...................................................................................30


4.2.4 ipv4SetDnsServer ...........................................................................................31
4.3 IPv6 manual configuration ......................................................................................32
4.3.1 ipv6SetLinkLocalAddr......................................................................................32
4.3.2 ipv6SetPrefix ...................................................................................................33
4.3.3 ipv6SetGlobalAddr ..........................................................................................34
4.3.4 ipv6SetRouter .................................................................................................35
4.3.5 ipv6SetDnsServer ...........................................................................................36
4.4 Socket API .............................................................................................................37
4.4.1 socketOpen .....................................................................................................37
4.4.2 socketSetTimeout ...........................................................................................38
4.4.3 socketSetTxBufferSize ....................................................................................39
4.4.4 socketSetRxBufferSize....................................................................................40
4.4.5 socketBindToInterface.....................................................................................41
4.4.6 socketBind ......................................................................................................42
4.4.7 socketConnect ................................................................................................43
4.4.8 socketListen ....................................................................................................45
4.4.9 socketAccept ...................................................................................................46
4.4.10 socketSend .....................................................................................................47
4.4.11 socketSendTo .................................................................................................49
4.4.12 socketReceive .................................................................................................51
4.4.13 socketReceiveFrom ........................................................................................52
4.4.14 socketReceiveEx.............................................................................................54
4.4.15 socketPoll........................................................................................................55
4.4.16 socketShutdown ..............................................................................................57
4.4.17 socketClose ....................................................................................................59
4.5 BSD Socket API .....................................................................................................61
4.5.1 socket .............................................................................................................61
4.5.2 bind .................................................................................................................61
4.5.3 connect ...........................................................................................................61
4.5.4 listen ...............................................................................................................61
4.5.5 accept .............................................................................................................61
4.5.6 send ................................................................................................................61
4.5.7 sendto .............................................................................................................61
4.5.8 recv .................................................................................................................61
4.5.9 recvfrom ..........................................................................................................61
4.5.10 select ..............................................................................................................61
4.5.11 setsockopt .......................................................................................................61
4.5.12 getsockopt.......................................................................................................61
4.5.13 shutdown.........................................................................................................61
4.5.14 close ...............................................................................................................61
4.6 Multicast Management ...........................................................................................62
4.6.1 ipJoinMulticastGroup .......................................................................................62
4.6.2 ipLeaveMulticastGroup....................................................................................63
4.7 Host Name Resolution ...........................................................................................64
4.7.1 getHostByName ..............................................................................................64
4.8 Address Conversion ...............................................................................................66
4.8.1 macStringToAddr ............................................................................................66
4.8.2 macAddrToString ............................................................................................67
4.8.3 ipStringToAddr ................................................................................................68
4.8.4 ipAddrToString ................................................................................................69

© 2010 - 2019 Oryx Embedded 3


CycloneTCP User Manual

1 Overview
1.1 CycloneTCP Features
CycloneTCP is a dual IPv4/IPv6 stack dedicated to embedded applications. CycloneTCP
conforms to RFC standards and offers seamless interoperability with existing TCP/IP
systems. By supporting IPv6, CycloneTCP eases deployment of next-generation Internet.
The stack is distributed as a full ANSI C and highly maintainable source code. Here are the
main features of the TCP/IP stack:

 Dual stack (IPv4 and/or IPv6)


 Built-in support for multiple network interfaces
 BSD style socket API
 Blocking/non-blocking socket operation and event-driven functions (select and poll)
 Efficient data transfer through zero copy
 Well-crafted TCP module with Nagle's algorithm and selective acknowledgement
 Raw socket interface
 Multicast support (IGMPv2 and MLDv1)
 IP fragmentation and reassembly support
 Flexible memory footprint. Built-time configuration to embed only the necessary
features
 High throughput
 Off-load checksum calculation (when supported by hardware) to accelerate
IP/TCP/UDP/ICMP checksum generation and verification
 Configurable memory model : Static scheme or dynamic memory allocation
 Dialog-based configuration wizard
 Portable architecture that supports industry-standard ARM® architectures (ARM7,
ARM9, CortexTM-M3 and CortexTM-M4).
 Straightforward port to any RTOS
 Debugging and trace functionality to ease development and integration
 Highly maintainable source code
 DHCP and SLAAC for dynamic address assignment and auto-configuration
 Add-on modules available (DNS client, DHCPv6, standard Internet services, SMTP
client, HTTP server, FTP server and client, Icecast client, SSL/TLS library)
 Supports industry-standard microcontrollers with built-in MAC as well as standalone
Ethernet controllers:

4 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

1.2 TCP/IP Basics


TCP/IP is an industry standard suite of protocols that is designed for large networks
consisting of network segments interconnected by routers. TCP/IP is the primary protocol
that is used on the Internet and is the most complete and accepted protocol available. It
provides end-to-end connectivity by specifying how payload data should be formatted,
transmitted, routed and received at the destination. TCP/IP adopts a layered model and is
usually seen as being composed of four layers:

 The link layer is the lowest layer and is responsible for moving data in and out across
a physical network (commonly Ethernet).
 The network layer is based on the Internet Protocol (IP). This layer is in charge of
delivering packets from a source host to a destination host across one or more
networks.
 The transport layer provides end-to-end communication between applications. The
most well-known transport protocol is the Transmission Control Protocol (TCP) that is
used for connection-oriented transmissions. The connectionless User Datagram
Protocol (UDP) is another common transport protocol used for simpler message-
based transmissions.
 The application layer contains the higher-level protocols used by most applications for
network communication. Some of the most popular ones are HTTP, FTP and SMTP.

HOST A SENDS DATA HOST B RECEIVES DATA

APPLICATION LAYER APPLICATION LAYER

TRANSPORT LAYER TRANSPORT LAYER

NETWORK LAYER NETWORK LAYER

LINK-LAYER LAYER LINK-LAYER LAYER

ETHERNET

FIGURE 1 TCP/IP MODEL

The Internet Protocol (IP) is implemented in two versions: IPv4 and IPv6. IPv4 is the most
widely deployed protocol but has limited address space (32-bit addresses). This limitation
motivates the development of the next-generation IPv6 protocol that features 128-bit
addresses.

© 2010 - 2019 Oryx Embedded 5


CycloneTCP User Manual

1.3 Socket Programming
Applications use so-called sockets to establish end-to-end point communication across a
network. Sockets programming is the most widely used abstraction to write client/server
applications that communicate each other.

HOST A HOST D

CLIENT
SOCKET SOCKET
APPLICATION

HOST B

CLIENT SERVER
SOCKET SOCKET
APPLICATION APPLICATION

HOST C

CLIENT
APPLICATION SOCKET SOCKET

FIGURE 2 SOCKET BASED CLIENT/SERVER APPLICATION

Socket API consists of standard functions that ease the burden of writing networking
applications (establish a connection or wait for connection attempts from a peer, write data,
read data, terminate a connection). A socket can be set up in either connection-oriented or
connectionless mode:

 Connection-oriented sockets use TCP as underlying transport protocol and provide a


reliable stream-based communication between hosts.
 Connectionless sockets are based on UDP and provide simple but unreliable transfer
mechanism. There is no guarantee of delivery, ordering, or duplicate protection.

Sockets may operate in one of two modes: blocking or non-blocking. A blocking socket will
not return control until it has sent (or received) some or all data specified for the operation.
Blocking mode may cause an application to hang if a socket is waiting for data that never
arrive. When operating in non-blocking mode, socket functions always return and are
guaranteed not to block the calling task.

6 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

1.4 Task Model


When CycloneTCP is used in conjunction with an RTOS, user applications and the stack
itself run in separate tasks. Thus, user tasks may block without interfering the TCP/IP stack.

User Application CycloneTCP


RX IRQ

TCP/IP TCP/IP
STACK STACK
USER USER USER
TASK 1 TASK 2 TASK 3 TIMER RX
TASK TASK

FIGURE 3 TASK MODEL

CycloneTCP adopts a two-task model. The first one handles periodic operations such as
ARP cache management, TCP packet retransmissions, IP fragment reassembly timeout or
multicast related operations. The second task is responsible for processing incoming
Ethernet frames when an RX interrupt is fired. As most of the processing is done at task
level, CycloneTCP minimizes interrupt lockout time and offers great real-time performances.

If the application makes use of multiple network interfaces, each interface owns a dedicated
RX task while periodic operations are still managed by the same task. This feature allows the
user to define a given priority for each network interface when processing incoming packets.

© 2010 - 2019 Oryx Embedded 7


CycloneTCP User Manual

1.5 Memory Management
Any TCP/IP stack continuously allocates or deallocates memory buffers when transferring
packets to/from the device. For that purpose, CycloneTCP features two different memory
allocation schemes.

1.5.1 Dynamic allocation


When dynamic memory allocation is selected, CycloneTCP delegates memory management
to the underlying RTOS by calling osAllocMem and osFreeMem functions. These functions
use heap memory allocation by default and can be redefined to use a custom memory
allocation scheme.

1.5.2 Memory pool


In embedded environments, memory pools are often used to manage memory allocation. A
memory pool consists of a list of fixed-size blocks of memory. When memory pool allocation
scheme is used, CycloneTCP reserves a static chunk of memory and does not call
osAllocMem and osFreeMem functions. To enable this feature,
NET_MEM_POOL_SUPPORT switch shall be set to ENABLED in the configuration file (refer
to Stack Configuration section for more details).

8 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

2 Using the stack


To integrate CycloneTCP to an existing project, it is recommended to follow the steps below.
Alternatively, one of the demonstration projects available in the CycloneTCP package can be
modified.

2.1 Source files


Unzip CycloneTCP archive and copy the contents of common/ and cyclone_tcp/ directory to
your project directory. Open your favorite IDE and add the necessary source files to your
project:

Folder Description
common/ Contains some features that are common to CycloneTCP and
CycloneSSL (endianness conversion functions, RTOS
abstraction layer, debugging facilities)
cyclone_tcp/core/ Contains the core features of the TCP/IP stack. All the files
included in this folder are mandatory and must be linked to
your project
cyclone_tcp/drivers/ Contains the supported Network controller drivers. Only pick
up the necessary driver files and discard others
cyclone_tcp/ipv4/ Adds support for IPv4. Link all the files from this folder if IPv4
support is desired
cyclone_tcp/ipv6/ Adds support for IPv6. Link all the files from this folder if IPv6
support is desired
cyclone_tcp/ppp/ Adds support for PPP
cyclone_tcp/dns/ Adds support for DNS
cyclone_tcp/mdns/ Adds support for mDNS (optional module)
cyclone_tcp/netbios/ Adds support for NetBIOS name system (optional module)
cyclone_tcp/dns_sd/ Adds support for DNS-SD (optional module)
cyclone_tcp/dhcp/ Adds support for DHCP client (optional module)
cyclone_tcp/dhcpv6/ Adds support for DHCPv6 client and relay agent (optional
module)
cyclone_tcp/ftp/ Adds support for FTP client/server (optional module)
cyclone_tcp/http/ Adds support for HTTP server (optional module)
cyclone_tcp/mqtt/ Adds support for MQTT client (optional module)
cyclone_tcp/smtp/ Adds support for SMTP client (optional module)
cyclone_tcp/snmp/ Adds support for SNMP agent (optional module)
cyclone_tcp/sntp/ Adds support for SNTP client (optional module)
cyclone_tcp/icecast/ Adds support for Icecast/SHOUTcast client (optional module)
cyclone_tcp/std_services/ Adds support for standard Internet services such as Echo,
Discard, Chargen and Daytime (optional module)

2.2 Project properties

Edit project properties and add the following directories to the include path:

 common/
 cyclone_tcp/

© 2010 - 2019 Oryx Embedded 9


CycloneTCP User Manual

2.3 RTOS configuration
If the underlying RTOS is supported by CycloneTCP, just create an empty os_port_config.h
header file and define preprocessor macro that matches your RTOS:

RTOS Preprocessor macro


ChibiOS #define USE_CHIBIOS
CMSIS-RTOS #define USE_CMSIS_RTOS
CMSIS-RTOS2 #define USE_CMSIS_RTOS2
FreeRTOS #define USE_FREERTOS
Keil RTX #define USE_RTX
Micrium µC/OS-II #define USE_UCOS2
Micrium µC/OS-III #define USE_UCOS3
Segger embOS #define USE_EMBOS
SYS/BIOS (TI-RTOS) #define USE_SYS_BIOS

Then, add the relevant source and header files to your project:

RTOS Dependencies
ChibiOS common/os_port_chibios.c
common/os_port_chibios.h
CMSIS-RTOS common/os_port_cmsis_rtos.c
common/os_port_cmsis_rtos.h
CMSIS-RTOS2 common/os_port_cmsis_rtos2.c
common/os_port_cmsis_rtos2.h
FreeRTOS common/os_port_freertos.c
common/os_port_freertos.h
Keil RTX common/os_port_rtx.c
common/os_port_rtx.h
Micrium µC/OS-II common/os_port_ucos2.c
common/os_port_ucos2.h
Micrium µC/OS-III common/os_port_ucos3.c
common/os_port_ucos3.h
Segger embOS common/os_port_embos.c
common/os_port_embos.h
SYS/BIOS (TI-RTOS) common/os_port_sys_bios.c
common/os_port_sys_bios.h

If your operating system is not supported, it will be necessary to port the RTOS by redefining
all the functions of the RTOS abstraction layer. For more details, refer to the dedicated
section.

10 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

2.4 Ethernet drivers


To use an Ethernet adapter with CycloneTCP, a specific driver is required. For supported
devices, simply include the corresponding driver source file to your project. It may be
necessary to change I/O assignment in the driver initialization routine to adapt to your
hardware.

2.4.1 Ethernet MAC drivers

Manufacturer Device Driver


Atmel® AVR32 drivers/mac/avr32_eth_driver.c
SAM3X drivers/mac/sam3x_eth_driver.c
SAM4E drivers/mac/sam4e_eth_driver.c
SAM7X drivers/mac/sam7x_eth_driver.c
SAM9263 drivers/mac/sam9263_eth_driver.c
SAMA5D2 drivers/mac/sama5d2_eth_driver.c
SAMA5D3 drivers/mac/sama5d3_eth_driver.c
SAME54 drivers/mac/same54_eth_driver.c
SAME70 drivers/mac/same70_eth_driver.c
SAMV71 drivers/mac/samv71_eth_driver.c
Cortus® APS3 drivers/mac/aps3_eth_driver.c
Espressif Systems® ESP32 drivers/mac/esp32_eth_driver.c
Freescale® Coldfire V2 (MCF5225x) drivers/mac/mcf5225x_eth_driver.c
Kinetis K6x drivers/mac/mk6x_eth_driver.c
Kinetis K7x drivers/mac/mk7x_eth_driver.c
Kinetis KV5x drivers/mac/mkv5x_eth_driver.c
i.MX RT1052 drivers/mac/mimxrt1052_eth_driver.c
Infineon® XMC4500 drivers/mac/xmc4500_eth_driver.c
XMC4700 drivers/mac/xmc4700_eth_driver.c
XMC4800 drivers/mac/xmc4800_eth_driver.c
Microsemi® SmartFusion A2F drivers/mac/a2fxxxm3_eth_driver.c
SmartFusion2 M2S drivers/mac/m2sxxx_eth_driver.c
Microchip® PIC32MX drivers/mac/pic32mx_eth_driver.c
PIC32MZ drivers/mac/pic32mz_eth_driver.c
NXP® LPC1750 drivers/mac/lpc175x_eth_driver.c
LPC1760 drivers/mac/lpc176x_eth_driver.c
LPC1800 drivers/mac/lpc18xx_eth_driver.c
LPC2300 drivers/mac/lpc23xx_eth_driver.c
LPC4300 drivers/mac/lpc43xx_eth_driver.c
Spansion® FM4 drivers/mac/fm4_eth_driver.c
Renesas® RX62N drivers/mac/rx62n_eth_driver.c
RX63N drivers/mac/rx63n_eth_driver.c
RZ/A1 drivers/mac/rza1_eth_driver.c
Synergy S7 drivers/mac/s7g2_eth_driver.c
STMicroelectronics® STM32F107 drivers/mac/stm32f107_eth_driver.c
STM32F207/217 drivers/mac/stm32f2x7_eth_driver.c
STM32F407/417 drivers/mac/stm32f4x7_eth_driver.c
STM32F429/439 drivers/mac/stm32f4x9_eth_driver.c
STM32F746/756 drivers/mac/stm32f7xx_eth_driver.c
STM32H743/753 drivers/mac/stm32h7xx_eth_driver.c

© 2010 - 2019 Oryx Embedded 11


CycloneTCP User Manual

STR912 drivers/mac/str912_eth_driver.c

Manufacturer Device Driver


Texas Instruments® Concerto F28M35x drivers/mac/f28m35x_eth_driver.c
Stellaris LM3S drivers/mac/lm3s_eth_driver.c
Tiva TM4C129X drivers/mac/tm4c129x_eth_driver.c
Sitara AM335x drivers/mac/am335x_eth_driver.c
Xilinx® Zynq-7000 drivers/mac/zynq7000_eth_driver.c

2.4.2 Ethernet PHY drivers

Manufacturer Device Driver


Atheros® AR8031 drivers/phy/ar8031_driver.c
Davicom® DM9161 drivers/phy/dm9161_driver.c
Micrel® KSZ8031 drivers/phy/ksz8031_driver.c
KSZ8041 drivers/phy/ksz8041_driver.c
KSZ8051 drivers/phy/ksz8051_driver.c
KSZ8061 drivers/phy/ksz8061_driver.c
KSZ8081 drivers/phy/ksz8081_driver.c
KSZ8091 drivers/phy/ksz8091_driver.c
KSZ8721 drivers/phy/ksz8721_driver.c
KSZ9031 drivers/phy/ksz9031_driver.c
SMSC® LAN8700 drivers/phy/lan8700_driver.c
LAN8710 drivers/phy/lan8710_driver.c
LAN8720 drivers/phy/lan8720_driver.c
LAN8740 drivers/phy/lan8740_driver.c
LAN8742 drivers/phy/lan8742_driver.c
Realtek® RTL8211 drivers/phy/rtl8211_driver.c
Renesas® uPD60611 drivers/phy/upd60611_driver.c
STMicroelectronics® ST802RT1A drivers/phy/st802rt1a_driver.c
Texas Instruments® DP83620 drivers/phy/dp83620_driver.c
DP83822 drivers/phy/dp83822_driver.c
DP83848 drivers/phy/dp83848_driver.c

2.4.3 Standalone Ethernet controllers

Manufacturer Device Driver


Davicom® DM9000A/B drivers/eth/dm9000.c
Micrel® KSZ8851 drivers/eth/ksz8851.c
Microchip® ENC28J60 drivers/eth/enc28j60.c
ENC624J600 drivers/eth/enc624j600.c

If your device is not supported by the TCP/IP stack, Oryx Embedded can guide you through
the process of writing your own Ethernet driver.

12 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

2.5 TCP/IP stack initialization

The main function must be modified in order to configure the TCP/IP stack properly:

void main(void)
{
error_t error;
MacAddr macAddr;
NetInterface *interface;

//Initialize kernel
osInitKernel();

//Initialize TCP/IP stack


error = netInit();
//Any error to report?
if(error)
{
//Error handling
}

//Configure the first Ethernet interface


interface = &netInterface[0];

//Set interface name


netSetInterfaceName(interface, "eth0");
//Select the relevant network adapter
netSetDriver(interface, &stm32f107EthDriver);
netSetPhyDriver(interface, &dp83848PhyDriver);
//Set host MAC address
macStringToAddr("00-AB-CD-EF-02-07", &macAddr);
netSetMacAddr(interface, &macAddr);

//Initialize network interface


error = netConfigInterface(interface);
//Failed to configure the interface?
if(error)
{
//Error handling
}

//DHCP initialization or manual configuration (IP address,


//subnet mask, default gateway and DNS servers) goes here
...

//The TCP/IP stack is now running


osStartKernel();
}

© 2010 - 2019 Oryx Embedded 13


CycloneTCP User Manual

3 Stack Configuration
The TCP/IP stack can be configured to embed only the necessary features. All configuration
parameters are located in a dedicated header file (net_config.h). This file is project specific
and can be modified without altering the behavior of other projects. All the compilation flags
are preconfigured to fit most applications. However, this default configuration can be
changed by overriding the desired compilation flags in the header file.

3.1 TCP/IP stack configuration


Compilation flag Default value Description
NET_INTERFACE_COUNT 1 Sets the number of network
interfaces. If the application
makes use of multiple network
adapters, the default value can be
changed to reflect the actual
number of interfaces.

NET_TICK_STACK_SIZE 550 Stack size (in words) required to


run the TCP/IP timer task. This
task handles periodic operations
such as ARP cache management,
TCP packet retransmissions and
IP fragment reassembly timeout.

NET_TICK_PRIORITY 1 Priority at which the TCP/IP timer


task should run.

NET_TICK_INTERVAL 100 Sets TCP/IP tick interval (in


milliseconds). A value of 100ms is
recommended.

NET_RX_STACK_SIZE 650 Stack size (in words) required to


run the TCP/IP RX task. This task
is responsible for processing
incoming Ethernet frames.

NET_RX_PRIORITY 2 Priority at which the TCP/IP RX


task should run. The RX task shall
be assigned a priority higher than
other tasks to minimize network
latencies.

14 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

3.2 Memory pool configuration


Compilation flag Default value Description
NET_MEM_POOL_SUPPORT DISABLED Sets whether memory pool
allocation shall be used to
manage network buffers. By
default, this option is disabled and
the memory allocation process is
handled by the underlying RTOS.

NET_MEM_POOL_BUFFER_COUNT 32 Configures the number of buffers


in the memory pool.

NET_MEM_POOL_BUFFER_SIZE 1536 Sets the size, in bytes, of the


buffers. A value a 1536 bytes is
recommended so that a buffer can
holds an entire Ethernet frame.
Smaller values may dramatically
decrease throughput.

3.3 IPv4 configuration


Compilation flag Default value Description
IPV4_SUPPORT ENABLED This switch adds or removes
support for IPv4.

IPV4_FILTER_MAX_SIZE 8 Defines the size of the IPv4 filter


table. If Multicast feature (IGMP)
is not used, this value can be
decreased.

IPV4_FRAG_SUPPORT DISABLED This flag tells whether IPv4


fragmentation is supported or not.

IPV4_MAX_FRAG_DATAGRAMS 4 Sets the maximum number of


fragmented packets the host will
accept and hold in the reassembly
queue simultaneously.

IPV4_MAX_FRAG_DATAGRAM_SIZE 8192 Maximum datagram size the host


will accept when reassembling
fragments.

IPV4_FRAG_TIME_TO_LIVE 15000 Maximum time an IPv4 fragment


can spend waiting to be
reassembled.

© 2010 - 2019 Oryx Embedded 15


CycloneTCP User Manual

3.4 ARP configuration
Compilation flag Default value Description
ARP_CACHE_SIZE 8 This flag determines the size of
the ARP cache. If the host deals
with many machines on the same
local network, this value can be
increased. However the lookup
operation to match IP with MAC
addresses will be longer.

ARP_MAX_PENDING_PACKETS 2 Maximum number of packets


waiting for address resolution to
complete.

3.5 IGMP configuration


Compilation flag Default value Description
IGMP_SUPPORT DISABLED This switch adds or removes
support for IGMP.

3.6 Auto-IP configuration


Compilation flag Default value Description
AUTO_IP_SUPPORT DISABLED This switch adds or removes
support for Auto-IP (dynamic
configuration of IPv4 link-local
addresses).

3.7 IPv6 configuration


Compilation flag Default value Description
IPV6_SUPPORT DISABLED This switch adds or removes
support for IPv6.

IPV6_FILTER_MAX_SIZE 8 Defines the size of the IPv6 filter


table. Since IPv6 makes abundant
use of Multicast, it is not
recommended to use a lower
value.

IPV6_FRAG_SUPPORT DISABLED This flag tells whether IPv6


fragmentation is supported or not.

IPV6_MAX_FRAG_DATAGRAMS 4 Sets the maximum number of


fragmented packets the host will
accept and hold in the reassembly
queue simultaneously.

16 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

IPV6_MAX_FRAG_DATAGRAM_SIZE 8192 Maximum datagram size the host


will accept when reassembling
fragments.

IPV6_FRAG_TIME_TO_LIVE 15000 Maximum time an IPv6 fragment


can spend waiting to be
reassembled.

3.8 NDP configuration


Compilation flag Default value Description
NDP_NEIGHBOR_CACHE_SIZE 8 Defines the size of the Neighbor
cache.

NDP_DEST_CACHE_SIZE 8 Defines the size of the Destination


cache.

NDP_MAX_PENDING_PACKETS 2 Maximum number of packets


waiting for address resolution to
complete.

3.9 MLD configuration


Compilation flag Default value Description
MLD_SUPPORT DISABLED This switch adds or removes
support for MLDv1.

3.10 SLAAC configuration


Compilation flag Default value Description
SLAAC_SUPPORT ENABLED This switch adds or removes
support for SLACC (IPv6
Stateless Address Auto-
configuration).

3.11 TCP configuration


Compilation flag Default value Description
TCP_SUPPORT ENABLED This switch adds or removes
support for TCP.

TCP_TICK_INTERVAL 100 Sets the TCP tick interval (in


milliseconds). A value of 100ms or
200ms is recommended.

TCP_MAX_MSS 1430 Maximum segment size, in bytes.


A value of 1430 bytes is
recommended to accommodate
both IPv4 and IPv6.

© 2010 - 2019 Oryx Embedded 17


CycloneTCP User Manual

TCP_DEFAULT_TX_BUFFER_SIZE 2860 Default buffer size for
transmission, in bytes. It is
preferable to use a multiple of the
MSS for efficiency purpose.

TCP_DEFAULT_RX_BUFFER_SIZE 2860 Default buffer size for reception, in


bytes. It is preferable to use a
multiple of the MSS for efficiency
purpose.

TCP_DEFAULT_SYN_QUEUE_SIZE 4 Default SYN queue size for


listening sockets.

TCP_MAX_SYN_QUEUE_SIZE 16 Maximum SYN queue size for


listening sockets.

TCP_MAX_RETRIES 5 Maximum number of


retransmissions. This value can
be increased to make the
communication more robust.

TCP_INITIAL_RTO 1000 Initial retransmission timeout (in


milliseconds). This value can be
increased up to 3s to
accommodate high latency
networks.

TCP_MIN_RTO 1000 Minimum retransmission timeout


(in milliseconds).

TCP_MAX_RTO 60000 Maximum retransmission timeout


(in milliseconds).

TCP_SACK_SUPPORT DISABLED This switch adds or removes


support for SACK.

3.12 UDP configuration


Compilation flag Default value Description
UDP_SUPPORT ENABLED This switch adds or removes
support for UDP.

UDP_RX_QUEUE_SIZE 4 Receive queue depth. This


parameter specifies the maximum
number of packets waiting in the
receive queue.

18 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

3.13 Socket configuration


Compilation flag Default value Description
SOCKET_MAX_COUNT 16 Maximum number of sockets that
can be opened simultaneously.

SOCKET_EPHEMERAL_PORT_MIN 49152 Lower limit for dynamic port range.

SOCKET_EPHEMERAL_PORT_MAX 65535 Upper limit for dynamic port range.

3.14 Raw socket configuration


Compilation flag Default value Description
RAW_SOCKET_SUPPORT ENABLED This switch adds or removes
support for raw sockets.

RAW_SOCKET_RX_QUEUE_SIZE 4 Receive queue depth. This


parameter specifies the maximum
number of packets waiting in the
receive queue.

© 2010 - 2019 Oryx Embedded 19


CycloneTCP User Manual

3.15 DNS cache configuration
Compilation flag Default value Description
DNS_CACHE_SIZE 8 Maximum number of entries in the
DNS cache.

DNS_MAX_LIFETIME 3600000 Maximum cache lifetime for DNS


entries (in milliseconds).

MDNS_MAX_LIFETIME 60000 Maximum cache lifetime for


mDNS entries (in milliseconds).

3.16 DNS client configuration


DNS_CLIENT_SUPPORT ENABLED This switch adds or removes
support for DNS client.

DNS_CLIENT_MAX_RETRIES 3 Maximum number of


retransmissions of DNS queries

DNS_CLIENT_INIT_TIMEOUT 1000 Initial retransmission timeout for


DNS queries (in milliseconds).

DNS_CLIENT_MAX_TIMEOUT 5000 Maximum retransmission timeout


for DNS queries (in milliseconds).

3.17 mDNS client configuration


MDNS_CLIENT_SUPPORT ENABLED This switch adds or removes
support for mDNS client.

MDNS_CLIENT_MAX_RETRIES 3 Maximum number of


retransmissions of mDNS queries

MDNS_CLIENT_INIT_TIMEOUT 1000 Initial retransmission timeout for


mDNS queries (in milliseconds).

MDNS_CLIENT_MAX_TIMEOUT 1000 Maximum retransmission timeout


for mDNS queries (in
milliseconds).

3.18 mDNS responder configuration


MDNS_RESPONDER_SUPPORT ENABLED This switch adds or removes
support for mDNS responder.

20 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

3.19 NetBIOS NS client configuration


NBNS_CLIENT_SUPPORT ENABLED This switch adds or removes
support for NBNS client.

NBNS _CLIENT_MAX_RETRIES 3 Maximum number of


retransmissions of NBNS queries

NBNS _CLIENT_INIT_TIMEOUT 1000 Initial retransmission timeout for


NBNS queries (in milliseconds).

NBNS _CLIENT_MAX_TIMEOUT 1000 Maximum retransmission timeout


for NBNS queries (in
milliseconds).

3.20 NetBIOS NS responder configuration


NBNS _RESPONDER_SUPPORT ENABLED This switch adds or removes
support for NBNS responder.

3.21 DNS-SD configuration


DNS_SD_SUPPORT DISABLED This switch adds or removes
support for DNS-based Service
Discovery.

DNS_SD_MAX_INSTANCE_LEN 32 Maximum length of the instance


name.

© 2010 - 2019 Oryx Embedded 21


CycloneTCP User Manual

4 Function reference
4.1 TCP/IP Stack Configuration
4.1.1 netInit

Syntax
error_t netInit(void)

Parameters
none

Return value
The netInit function returns NO_ERROR if the TCP/IP stack has been successfully initialized.
Otherwise a non-zero status code describing the error is returned.

Description
The netInit function initializes the TCP/IP stack and allocates the necessary resources. This
routine must be called before any other TCP/IP related functions.

Example
void main(void)
{
error_t error;

//Initialize TCP/IP stack


error = netInit();

//Any error to report?


if(error)
{
//Error handling
}

//Configure network interfaces


//...

//The TCP/IP stack is now running


osStart();
}

22 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

4.1.2 netConfigInterface

Syntax
error_t netConfigInterface(NetInterface *interface)

Parameters
Interface [in] Pointer to the network interface to be configured.

Return value
The netConfigInterface function returns NO_ERROR if the specified network interface has
been successfully configured. Otherwise a non-zero status code describing the error is
returned.

Description
The netConfigInterface function configures the underlying network driver and performs
interface-specific initialization. Before calling this function, the interface driver and the MAC
address of the interface must properly set.

If address auto-configuration is used (DHCP for IPv4, SLAAC and/or DHCPv6 pour IPv6),
the network interface does not require any further action. Otherwise the following parameters
should be manually configured:
 IP address, subnet mask, default gateway and DNS servers (for IPv4)
 Link-local address, global address, prefix, router and DNS servers (for IPv6)

Example
error_t error;
MacAddr macAddr;

//Configure the first Ethernet interface


NetInterface *interface = &netInterface[0];

//Set interface name


netSetInterfaceName(interface, "eth0");
//Select the relevant network adapter
netSetDriver(interface, &sam3xEthDriver);
netSetPhyDriver(interface, &dm9161PhyDriver);
//Set host MAC address
macStringToAddr("00-AB-CD-EF-02-07", &macAddr);
netSetMacAddr(interface, &macAddr);

//Initialize network interface


error = netConfigInterface(interface);

//Failed to configure the interface?


if(error)
{
//Error handling
}

© 2010 - 2019 Oryx Embedded 23


CycloneTCP User Manual

4.1.3 netSetInterfaceName

Syntax
error_t netSetInterfaceName(NetInterface *interface,
const char_t *name)

Parameters
interface Pointer to the network interface to be configured.

name NULL-terminated string that contains the interface name.

Return value
The netSetInterfaceName function returns NO_ERROR if the interface has been successfully
renamed. Otherwise a non-zero status code describing the error is returned.

Description
By default, network interfaces are named eth0, eth1, etc. The netSetInterfaceName function
can be used to customize the name of the network interface.

Example
NetInterface *interface;

//Select the first network interface


interface = &netInterface[0];

//Rename the network interface


netSetInterfaceName(interface, "wlan0");

24 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

4.1.4 netSetDriver

Syntax
error_t netSetDriver(NetInterface *interface,
const NicDriver *driver)

Parameters
interface Pointer to the network interface to be configured.

driver Ethernet MAC driver.

Return value
The netSetDriver function returns NO_ERROR if the device driver has been successfully
assigned. Otherwise a non-zero status code describing the error is returned.

Description
The netSetDriver function is used to assign a device driver to the specified interface. This
function must be called before calling the netConfigInterface function

Example
Refer to netConfigInterface fonction

© 2010 - 2019 Oryx Embedded 25


CycloneTCP User Manual

4.1.5 netSetPhyDriver

Syntax
error_t netSetPhyDriver (NetInterface *interface,
const PhyDriver *driver)

Parameters
interface Pointer to the network interface to be configured.

driver Ethernet PHY driver.

Return value
The netSetPhyDriver function returns NO_ERROR if the PHY device driver has been
successfully assigned. Otherwise a non-zero status code describing the error is returned.

Description
The netSetPhyDriver function is used to assign a PHY device driver to the specified
interface. For Ethernet controllers with integrated MAC + PHY, this function should not be
called.

Example
Refer to netConfigInterface fonction

26 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

4.1.6 netSetMacAddr

Syntax
error_t netSetMacAddr(NetInterface *interface,
const MacAddr *macAddr)

Parameters
interface Pointer to the network interface whose MAC address is to be configured.

driver MAC address.

Return value
The netSetMacAddr function returns NO_ERROR if the MAC address has been successfully
assigned. Otherwise a non-zero status code describing the error is returned.

Description
The netSetMacAddr function is used to assign a MAC address to the specified interface. For
Ethernet controller with factory preprogrammed MAC address, this function should not be
called.

Example
Refer to netConfigInterface fonction

© 2010 - 2019 Oryx Embedded 27


CycloneTCP User Manual

4.2 IPv4 manual configuration
4.2.1 ipv4SetHostAddr

Syntax
error_t ipv4SetHostAddr(NetInterface *interface, Ipv4Addr addr)

Parameters
interface Pointer to the network interface whose host address is to be configured.

addr IPv4 host address.

Return value
The ipv4SetHostAddr function returns NO_ERROR if the IPv4 address has been
successfully assigned. Otherwise a non-zero status code describing the error is returned.

Description
The ipv4SetHostAddr function is used to manually assign an IPv4 address. This function
should not be called when the DHCP client is running. The currently assigned IPv4 address
can be retrieved using the ipv4GetHostAddr function.

Example
error_t error;
Ipv4Addr ipv4Addr;

//Select the first Ethernet interface


NetInterface *interface = &netInterface[0];

//Initialize network interface


error = netConfigInterface(interface);
//Any error to report?
if(!socket) {...}

//Set IPv4 host address


ipv4StringToAddr("192.168.0.10", &ipv4Addr);
ipv4SetHostAddr(interface, ipv4Addr);

//Set subnet mask


ipv4StringToAddr("255.255.255.0", &ipv4Addr);
ipv4SetSubnetMask(interface, ipv4Addr);

//Set default gateway


ipv4StringToAddr("192.168.0.254", &ipv4Addr);
ipv4SetDefaultGateway(interface, ipv4Addr);

28 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

4.2.2 ipv4SetSubnetMask

Syntax
error_t ipv4SetSubnetMask(NetInterface *interface, Ipv4Addr mask)

Parameters
interface Pointer to the network interface whose subnet mask is to be configured.

mask Subnet mask

Return value
The ipv4SetSubnetMask function returns NO_ERROR if the subnet mask has been
successfully updated. Otherwise a non-zero status code describing the error is returned.

Description
The ipv4SetSubnetMask is used to manually configure the subnet mask. This function should
not be called when the DHCP client is running. The current subnet mask can be retrieved
using the ipv4GetSubnetMask function.

Example
Refer to ipv4SetHostAddr function

© 2010 - 2019 Oryx Embedded 29


CycloneTCP User Manual

4.2.3 ipv4SetDefaultGateway

Syntax
error_t ipv4SetDefaultGateway(NetInterface *interface, Ipv4Addr addr)

Parameters
interface Pointer to the network interface to be configured.

addr IPv4 address of the default gateway.

Return value
The ipv4SetDefaultGateway function returns NO_ERROR if the address of gateway has
been successfully updated. Otherwise a non-zero status code describing the error is
returned.

Description
The ipv4SetDefaultGateway is used to manually assign the IPv4 address of the gateway.
This function should not be called when the DHCP client is running. The currently assigned
address can be retrieved using the ipv4GetDefaultGateway function.

Example
Refer to ipv4SetHostAddr function

30 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

4.2.4 ipv4SetDnsServer

Syntax
error_t ipv4SetDnsServer(NetInterface *interface, uint_t num,
Ipv4Addr addr)

Parameters
interface Pointer to the network interface to be configured.

num This parameter selects between the primary and secondary DNS server.

addr IPv4 address of the DNS server.

Return value
The ipv4SetDnsServer function returns NO_ERROR if the address of DNS server has been
successfully updated. Otherwise a non-zero status code describing the error is returned.

Description
The ipv4SetDnsServer is used to manually assign the IPv6 address of the primary or the
secondary DNS server. This function should not be called when the DHCP client is running.
The currently assigned address can be retrieved using the ipv4GetDnsServer function.

Example
error_t error;
Ipv4Addr ipv4Addr;

//Select the first Ethernet interface


NetInterface *interface = &netInterface[0];

//Primary DNS server


ipv4StringToAddr("8.8.4.4", &ipv4Addr);
ipv4SetDnsServer(interface, 0, ipv4Addr);

//Secondary DNS server


ipv4StringToAddr ("8.8.8.8", &ipv4Addr);
ipv4SetDnsServer(interface, 1, ipv4Addr);

© 2010 - 2019 Oryx Embedded 31


CycloneTCP User Manual

4.3 IPv6 manual configuration
4.3.1 ipv6SetLinkLocalAddr

Syntax
error_t ipv6SetLinkLocalAddr(NetInterface *interface,
const Ipv6Addr *addr)

Parameters
interface Pointer to the network interface to be configured.

addr Link-local address.

Return value
The ipv6SetLinkLocalAddr function returns NO_ERROR if the link-local address has been
successfully assigned. Otherwise a non-zero status code describing the error is returned.

Description
The ipv6SetLinkLocalAddr function is used to manually assign the link-local address. The
current link-local address can be retrieved using the ipv6GetLinkLocalAddr function.

Example
error_t error;
Ipv6Addr ipv6Addr;

//Select the first Ethernet interface


NetInterface *interface = &netInterface[0];

//Initialize network interface


error = netConfigInterface(interface);
//Any error to report?
if(!socket) {...}

//Set link-local address


ipv6StringToAddr("fe80::1234", &ipv6Addr);
ipv6SetLinkLocalAddr(interface, &ipv6Addr);

//Set IPv6 prefix


ipv6StringToAddr(2001:db8:0:85a3::", &ipv6Addr);
ipv6SetPrefix(interface, &ipv6Addr, 64);

//Set global address


ipv6StringToAddr("2001:db8:0:85a3::1234", &ipv6Addr);
ipv6SetGlobalAddr(interface, &ipv6Addr);

//Set router
ipv6StringToAddr("fe80::1111:2222", &ipv6Addr);
ipv6SetRouter(interface, &ipv6Addr);

32 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

4.3.2 ipv6SetPrefix

Syntax
error_t ipv6SetPrefix(NetInterface *interface,
const Ipv6Addr *prefix, uint_t length)

Parameters
interface Pointer to the network interface whose subnet mask is to be configured.

prefix IPv6 prefix

prefixLength Prefix length

Return value
The ipv6SetPrefix function returns NO_ERROR if the IPv6 prefix has been successfully
updated. Otherwise a non-zero status code describing the error is returned.

Description
The ipv6SetPrefix is used to manually configure the IPv6 prefix. The current IPv6 prefix can
be retrieved using the ipv6GetPrefix function.

Example
Refer to ipv6SetLinkLocalAddr function

© 2010 - 2019 Oryx Embedded 33


CycloneTCP User Manual

4.3.3 ipv6SetGlobalAddr

Syntax
error_t ipv6SetGlobalAddr(NetInterface *interface, const Ipv6Addr *addr)

Parameters
interface Pointer to the network interface whose IPv6 global address is to be
configured.

addr Global address

Return value
The ipv6SetGlobalAddr function returns NO_ERROR if the global address has been
successfully updated. Otherwise a non-zero status code describing the error is returned.

Description
The ipv6SetGlobalAddr is used to manually configure the IPv6 global address. The currently
assigned address can be retrieved using the ipv6GetGlobalAddr function.

Example
Refer to ipv6SetLinkLocalAddr function

34 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

4.3.4 ipv6SetRouter

Syntax
error_t ipv6SetRouter(NetInterface *interface, const Ipv6Addr *addr)

Parameters
interface Pointer to the network interface to be configured.

addr Router address

Return value
The ipv6SetRouter function returns NO_ERROR if the address of the IPv6 router has been
successfully updated. Otherwise a non-zero status code describing the error is returned.

Description
The ipv6SetRouter is used to manually assign the address of the IPv6 router. The currently
assigned address can be retrieved using the ipv6GetRouter function.

Example
Refer to ipv6SetLinkLocalAddr function

© 2010 - 2019 Oryx Embedded 35


CycloneTCP User Manual

4.3.5 ipv6SetDnsServer

Syntax
error_t ipv6SetDnsServer (NetInterface *interface, uint_t num,
const Ipv6Addr *addr)

Parameters
interface Pointer to the network interface to be configured.

num This parameter selects between the primary and secondary DNS server.

addr IPv6 address of the DNS server.

Return value
The ipv6SetDnsServer function returns NO_ERROR if the address of DNS server has been
successfully updated. Otherwise a non-zero status code describing the error is returned.

Description
The ipv6SetDnsServer is used to manually assign the IPv6 address of the primary or the
secondary DNS server. The currently assigned address can be retrieved using the
ipv6GetDnsServer function.

Example
error_t error;
Ipv6Addr ipv6Addr;

//Select the first Ethernet interface


NetInterface *interface = &netInterface[0];

//Primary DNS server


ipv6StringToAddr("2001:4860:4860::8844", &ipv6Addr);
ipv6SetDnsServer(interface, 0, &ipv6Addr);

//Secondary DNS server


ipv6StringToAddr("2001:4860:4860::8888", &ipv6Addr);
ipv6SetDnsServer(interface, 1, &ipv6Addr);

36 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

4.4 Socket API


4.4.1 socketOpen

Syntax
Socket *socketOpen(uint_t type, uint_t protocol)

Parameters
type The type specification for the new socket. This parameter can be one of
the following values:
 SOCKET_TYPE_STREAM for connected sockets (TCP)
 SOCKET_TYPE_DGRAM for connectionless sockets (UDP)
 SOCKET_TYPE_RAW_IP for sending/receiving raw IP packets
 SOCKET_TYPE_RAW_ETH for sending/receiving raw Ethernet
packets

protocol The protocol to be used:


 SOCKET_IP_PROTO_TCP for connected sockets only
 SOCKET_IP_PROTO_UDP for connectionless sockets only
 SOCKET_IP_PROTO_ICMP
 SOCKET_IP_PROTO_IGMP
 SOCKET_IP_PROTO_ICMPV6

Return value
If no error occurs, socketOpen returns a valid pointer referencing the new socket. Otherwise,
NULL is returned.

Description
The socketOpen creates a socket bound to the specified protocol. The created socket can
operate in either connection-oriented or connectionless mode. Connection-oriented sockets
use TCP as underlying transport protocol and provide a reliable stream-based
communication between hosts. Connectionless sockets are based on UDP and provide
simple but unreliable transfer mechanism. There is no guarantee of delivery, ordering, or
duplicate protection. Raw sockets are special sockets that allow direct sending and receiving
of raw IP packets.

Example
Socket *socket;

//Create a connectionless socket


socket = socketOpen(SOCKET_TYPE_DGRAM, SOCKET_IP_PROTO_UDP);

//Failed to create socket?


if(!socket)
{
//Error handling
}

© 2010 - 2019 Oryx Embedded 37


CycloneTCP User Manual

4.4.2 socketSetTimeout

Syntax
error_t socketSetTimeout(Socket *socket, systime_t timeout)

Parameters
socket Valid handle referencing a socket.

timeout Maximum time to wait in milliseconds for any subsequent socket


operation. INFINITE_DELAY specifies an infinite timeout whereas a
value of zero forces the socket to operate in non-blocking mode.

Return value
If the timeout value has been successfully updated, NO_ERROR is returned. Otherwise a
non-zero status code describing the error is returned.

Description
The socketSetTimeout function is called to define a timeout limit when performing socket
operations. When a value non-zero is specified, socket functions (socketConnect,
socketAccept, socketSend, socketSendTo, socketReceive, socketReceiveFrom) are
guaranteed not to block for a time longer than timeout. In the case a socket operation timed
out, an ERROR_TIMEOUT status code will be returned. When timeout is zero, the socket
operates in non-blocking mode and will never block.

Example
error_t error;
Socket *socket;
IpAddr serverIpAddr;

//Server address
ipStringToAddr("192.168.0.100", &serverIpAddr);

//Create a connection-oriented socket


socket = socketOpen(SOCKET_TYPE_STREAM, SOCKET_IP_PROTO_TCP);
//Failed to create socket?
if(!socket) {...}

//Define a 15s timeout for all blocking operations


error = socketSetTimeout(socket, 15000);
//Any error to report?
if(error) {...}

//Establish a connection with the specified server. The operation


//will not block for a time longer than 15s...
error = socketConnect(socket, &serverIpAddr, 80);
//Check whether the connection succeeded
if(error) {...}

38 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

4.4.3 socketSetTxBufferSize

Syntax
error_t socketSetTxBufferSize(Socket *socket, size_t size)

Parameters
socket Valid handle referencing a socket.

size Desired buffer size in bytes

Return value
If the TX buffer size has been successfully updated, NO_ERROR is returned. Otherwise a
non-zero status code describing the error is returned.

Description
The socketSetTxBufferSize can be used to tune the size of the send buffer for any
connection-oriented socket. The size of the buffer can no longer be changed once the
connection has been established.

Example
error_t error;
Socket *socket;
IpAddr serverIpAddr;

//Server address
ipStringToAddr("192.168.0.100", &serverIpAddr);

//Create a connection-oriented socket


socket = socketOpen(SOCKET_TYPE_STREAM, SOCKET_IP_PROTO_TCP);
//Failed to create socket?
if(!socket) {...}

//Use a large buffer for transmitting data


error = socketSetTxBufferSize(socket, 6 * 1430);
//Any error to report?
if(error) {...}

//Establish a connection with the specified server


error = socketConnect(socket, &serverIpAddr, 80);
//Check whether the connection succeeded
if(error) {...}

© 2010 - 2019 Oryx Embedded 39


CycloneTCP User Manual

4.4.4 socketSetRxBufferSize

Syntax
error_t socketSetRxBufferSize(Socket *socket, size_t size)

Parameters
socket Valid handle referencing a socket.

size Desired buffer size in bytes

Return value
If the RX buffer size has been successfully updated, NO_ERROR is returned. Otherwise a
non-zero status code describing the error is returned.

Description
The socketSetRxBufferSize can be used to tune the size of the receive buffer for any
connection-oriented socket. The size of the buffer can no longer be changed once the
connection has been established.

Example
error_t error;
Socket *socket;
IpAddr serverIpAddr;

//Server address
ipStringToAddr("192.168.0.100", &serverIpAddr);

//Create a connection-oriented socket


socket = socketOpen(SOCKET_TYPE_STREAM, SOCKET_IP_PROTO_TCP);
//Failed to create socket?
if(!socket) {...}

//Use a large buffer for receiving data


error = socketSetRxBufferSize(socket, 6 * 1430);
//Any error to report?
if(error) {...}

//Establish a connection with the specified server


error = socketConnect(socket, &serverIpAddr, 80);
//Check whether the connection succeeded
if(error) {...}

40 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

4.4.5 socketBindToInterface

Syntax
error_t socketBindToInterface(Socket *socket,
NetInterface *interface)

Parameters
socket Valid handle referencing a socket.

interface Network interface to be used explicitly.

Return value
The socketBindToInterface function returns NO_ERROR if the socket has been successfully
associated with the specified interface. Otherwise a non-zero status code describing the
error is returned.

Description
By default, a socket accepts data, regardless the network interface the request arrives and
automatically chooses the most appropriate interface when sending data. The
socketBindToInterface function can be called to explicitly assign a specific network interface
to a socket. An explicitly bound socket accepts data only from the interface the socket is
associated with, and sends data to this particular interface only.

Example
Socket *socket;

//Create a connectionless socket


socket = socketOpen(SOCKET_TYPE_DGRAM, SOCKET_IP_PROTO_UDP);
//Failed to create socket?
if(!socket) {...}

//Associate the newly created socket with the third interface


error = socketBindToInterface(socket, &netInterface[2]);
//Any error to report?
if(error) {...}

© 2010 - 2019 Oryx Embedded 41


CycloneTCP User Manual

4.4.6 socketBind

Syntax
error_t socketBind(Socket *socket, const IpAddr *localIpAddr,
uint16_t localPort)

Parameters
socket Valid handle referencing a socket.

localIpAddr Local address to assign to the bound socket. The wildcard IP address
IP_ADDR_ANY can be specified to associate the socket only with a port
number.

localPort Local port number to assign to the bound socket.

Return value
The socketBind function returns NO_ERROR if the socket has been successfully associated
with the specified address. Otherwise a non-zero status code describing the error is returned.

Description
The socketBind function is required on an unconnected socket before subsequent calls to the
socketListen function. It is normally used to bind to either connection-oriented (stream) or
connectionless (datagram) sockets.

Example
error_t error;
Socket *serverSocket;
Socket *clientSocket;
IpAddr clientIpAddr;
uint16_t clientPort;

//Create a connection-oriented socket


serverSocket = socketOpen(SOCKET_TYPE_STREAM, SOCKET_IP_PROTO_TCP);
//Failed to create socket?
if(!serverSocket) {...}

//Bind the newly created socket to port 80


error = socketBind(serverSocket, &IP_ADDR_ANY, 80);
//Any error to report?
if(error) {...}

//Place socket in listening state


error = socketListen(serverSocket, 0);
//Any error to report?
if(error) {...}

//Accept an incoming connection


clientSocket = socketAccept(serverSocket, &clientIpAddr, &clientPort);

42 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

4.4.7 socketConnect

Syntax
error_t socketConnect(Socket *socket, const IpAddr *remoteIpAddr,
uint16_t remotePort)

Parameters
socket Valid handle referencing a socket.

remoteIpAddr IP address of the remote host.

remotePort Remote port number that will be used to establish the connection.

Return value
The socketConnect function returns NO_ERROR if the connection succeeds. Otherwise a
non-zero status code describing the error is returned.

Description
The socketConnect function is normally used to establish a connection with the specified
remote host.

For connectionless sockets, the operation performed by socketConnect is merely to establish


a default destination address that can be used on subsequent socketSend and
socketReceive calls. Any datagrams received from an address other than the specified
remote address will be discarded.

Stream sockets can call socketConnect only once, but datagram sockets can call
socketConnect multiple times to change their association.

© 2010 - 2019 Oryx Embedded 43


CycloneTCP User Manual

Example
error_t error;
Socket *socket;
IpAddr serverIpAddr;

//SMTP server address


error = ipStringToAddr("192.168.0.100", &serverIpAddr);
//Failed to convert the string to a valid IP address?
if(error) {...}

//Create a connection-oriented socket


socket = socketOpen(SOCKET_TYPE_STREAM, SOCKET_IP_PROTO_TCP);
//Failed to create socket?
if(!socket) {...}

//Establish a connection with the specified server


error = socketConnect(socket, &serverIpAddr, 25);
//Check whether the connection succeeded
if(error) {...}

//Initiate a conversation with the mail server


error = socketSend(socket, "EHLO [127.0.0.1]\r\n", 18, NULL, 0);
//Any error to report?
if(error) {...}

44 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

4.4.8 socketListen

Syntax
error_t socketListen(Socket *socket, uint_t backlog)

Parameters
socket Valid handle referencing a socket.

backlog The maximum length of the pending connection queue. If this parameter
is zero, then the default backlog value is used instead

Return value
The socketListen function returns NO_ERROR if the socket has been successfully placed
into listening mode. Otherwise a non-zero status code describing the error is returned.

Description
The socketListen function causes a socket to listen for incoming connection attempts. This
function is only necessary for connection-oriented sockets

Example
Refer to socketBind function

© 2010 - 2019 Oryx Embedded 45


CycloneTCP User Manual

4.4.9 socketAccept

Syntax
Socket *socketAccept(Socket *socket, IpAddr *clientIpAddr,
uint16_t *clientPort)

Parameters
socket Valid handle referencing a socket.

clientIpAddr Optional pointer to a structure that receives the IP address of the


connecting entity (can be NULL).

clientPort Optional pointer to a 16-bit integer that receives the port number used by
the client (can be NULL).

Return value
The function returns a handle to the socket in which the actual connection is made. If the
timeout expires and the connection request queue is still empty, NULL is returned.

Description
When passive socket is listening to for incoming connection attempts, the socketAccept
retrieve the first pending connection request and return the corresponding socket. If the
socketSetTimeout function has been previously called, socketAccept will block the task for
specified amount of time before returning. If non connection requests are pending in the
queue, NULL is returned.

Example
Refer to socketBind function

46 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

4.4.10 socketSend

Syntax
error_t socketSend(Socket *socket, const void *data,
uint_t length, uint_t *written, uint_t flags)

Parameters
socket Valid handle referencing a connected socket.

data Pointer to a buffer containing the data to be transmitted.

length Number of data bytes to send.

written Actual number of bytes sent (optional parameter, can be NULL).

flags A set of flags that influences the behavior of this function. For most
applications, a value of 0 is recommended.

Return value
The socketSend function returns NO_ERROR if the specified data has been successfully
sent. Otherwise a non-zero status code describing the error is returned.

Description
The socketSend function sends data on a connected socket. If the socket operates in
blocking mode, the function will not return until all the specified data has been sent (or at
least buffered for connection-oriented sockets). If the write operation timed out, the
ERROR_TIMEOUT status code is returned. The written parameter always reflects the actual
number of bytes that have been processed. In non-blocking mode, the socket sends as many
data bytes as possible without blocking and return immediately.

For connection-oriented socket, the flag SOCKET_FLAG_WAIT_ACK causes the function to


wait for an acknowledgement from the remote side before returning

Example
#define SERVER_NAME "www.oryx-embedded.com"
#define SERVER_PORT 80
#define REQUEST_URI "/test.php"

error_t error;
size_t length;
uint8_t buffer[256];
Socket *socket;
IpAddr serverIpAddr;

//Resolve HTTP server name


error = getHostByName(NULL, SERVER_NAME, &serverIpAddr, 0);
//Address resolution failed?
if(error) {...}

© 2010 - 2019 Oryx Embedded 47


CycloneTCP User Manual

//Create a connection-oriented socket
socket = socketOpen(SOCKET_TYPE_STREAM, SOCKET_IP_PROTO_TCP);
//Failed to create socket?
if(!socket) {...}

//Connect to the HTTP server


error = socketConnect(socket, &serverIpAddr, SERVER_PORT);
//Connection to server failed?
if(error) {...}

//Format HTTP request


length = sprintf(buffer, "GET %s HTTP/1.0\r\nHost: %s:%u\r\n\r\n",
REQUEST_URI, SERVER_NAME, SERVER_PORT);

//Send HTTP request


error = socketSend(socket, buffer, length, NULL, 0);
//Any error to report?
if(error) {...}

//Parse HTTP response header


while(1)
{
//Read the header line by line
error = socketReceive(socket, buffer, sizeof(buffer) - 1,
&length, SOCKET_FLAG_BREAK_CRLF);
//End of stream?
if(error) break;

//Properly terminate the string with a NULL character


buffer[length] = '\0';

//Check whether the end of the header has been reached


if(!strcmp(buffer, "\r\n"))
break;
}

//Parse HTTP response body


while(1)
{
//Read response body
error = socketReceive(socket, buffer, sizeof(buffer), &length, 0);
//End of stream?
if(error) break;
}

//Close the connection


socketClose(socket);

48 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

4.4.11 socketSendTo

Syntax
error_t socketSendTo(Socket *socket, const IpAddr *destIpAddr,
uint16_t destPort, const void *data, uint_t length,
uint_t *written, uint_t flags)

Parameters
socket Valid handle referencing a socket.

destIpAddr IP address of the target host.

destPort Target port number.

data Pointer to a buffer containing the data to be transmitted.

length Number of data bytes to send.

written Actual number of bytes sent (optional parameter, can be NULL).

flags A set of flags that influences the behavior of this function. For most
applications, a value of 0 is recommended.

Return value
The socketSendTo function returns NO_ERROR if the specified data has been successfully
sent. Otherwise a non-zero status code describing the error is returned.

Description
The socketSendTo function writes outgoing data to the specified host. For datagram
(connection-oriented) sockets, the remoteIpAddr parameter can specify either a unicast,
multicast or broadcast address. For stream (connection-oriented) sockets, remoteIpAddr and
remotePort are ignored making socketSendTo equivalent to socketSend.

© 2010 - 2019 Oryx Embedded 49


CycloneTCP User Manual

Example
error_t error;
Socket *socket;

//Open a connectionless socket


socket = socketOpen(SOCKET_TYPE_DGRAM, SOCKET_IP_PROTO_UDP);
//Failed to open socket?
if(!socket) {...}

//Server IP address
error = ipStringToAddr("fe80::1234:5678:abcd", &serverIpAddr);
//Failed to convert the string to a valid IP address?
if(error) {...}

//Send a datagram to the discard server (UDP port 9)


error = socketSendTo(socket, &serverIpAddr, 9,
"Hello world!", 12, NULL, 0);
//Any error to report?
if(error) {...}

//Close the socket


socketClose(socket);

50 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

4.4.12 socketReceive

Syntax
error_t socketReceive(Socket *socket, void *data,
uint_t size, uint_t *received, uint_t flags)

Parameters
socket Valid handle referencing a connected socket.

data Pointer to the buffer where to store the incoming data.

size Maximum number of bytes that can be received.

received Actual number of bytes that have been received.

flags A set of flags that influences the behavior of this function. For most
applications, a value of 0 is recommended.

Return value
The socketReceive function returns NO_ERROR if some or all of the requested data has
been successfully received. Otherwise a non-zero status code describing the error is
returned.

Description
The socketReceive function receives data from a connected socket. If the socket operates in
blocking mode, the function will not return until it has received some or all data specified for
the operation. It is normal for a blocking socket not to receive all the requested data. The
received parameter always reflects the actual number of bytes that have been read. In non-
blocking mode, the function reads as much data as possible without blocking and returns
immediately.

When the SOCKET_FLAG_PEEK is set, the data is copied into the buffer, but is not
removed from the input queue.

When the SOCKET_FLAG_WAIT_ALL flag is specified, the read operation will complete only
if the buffer supplied by the caller is completely full, or the connection is closed, or the
timeout expires. This flags is meaningless for connectionless sockets.

The SOCKET_FLAG_BREAK_CHAR(c) flag causes the function to stop reading data as


soon as the specified break character c is encountered. This flag is particularly useful to
perform line-by-line processing (HTTP headers, SMTP multiline responses, etc) or to simply
parse an HTTP POST request.

Example
Refer to socketSend function

© 2010 - 2019 Oryx Embedded 51


CycloneTCP User Manual

4.4.13 socketReceiveFrom

Syntax
error_t socketReceiveFrom(Socket *socket, IpAddr *srcIpAddr,
uint16_t *srcPort, void *data, uint_t size, uint_t *received,
uint_t flags)

Parameters
socket Valid handle referencing a socket.

srcIpAddr Optional pointer to a structure that receives the source IP address of the
incoming datagram (can be NULL).

srcPort Optional pointer to a 16-bit integer that receives the source port number
of the incoming datagram (can be NULL).

data Pointer to the buffer where to store the incoming data.

size Maximum number of bytes that can be received.

received Actual number of bytes that have been received.

flags A set of flags that influences the behavior of this function. For most
applications, a value of 0 is recommended.

Return value
The socketReceiveFrom function returns NO_ERROR if some data has been successfully
received. Otherwise a non-zero status code describing the error is returned.

Description
The socketReceiveFrom function receives a message from a connectionless socket. If no
messages are available in the receive queue, the socket wait for a message to arrive, unless
the socket is non-blocking in which case the function returns immediately.

When the SOCKET_FLAG_PEEK is set, the data is copied into the buffer, but is not
removed from the input queue.

52 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

Example
error_t error;
size_t length;
char_t s[40];
uint8_t buffer[256];
Socket *socket;
IpAddr clientIpAddr;
uint16_t clientPort;

//Create a connectionless socket


socket = socketOpen(SOCKET_TYPE_DGRAM, SOCKET_IP_PROTO_UDP);
//Failed to create socket?
if(!socket) {...}

//The discard server listen for incoming datagrams on port 9


error = socketBind(socket, &IP_ADDR_ANY, 9);
//Unable to bind the socket to the desired port?
if(error) {...}

//Endless loop
while(1)
{
//Wait for an incoming datagram
error = socketReceiveFrom(socket, &clientIpAddr,
&clientPort, buffer, sizeof(buffer), &length, 0);

//Any datagram received?


if(!error)
{
//Throw away any received datagram
printf("Discarding %d bytes from %s port %d...\r\n",
length, ipAddrToString(&clientIpAddr, s), clientPort);
}
}

© 2010 - 2019 Oryx Embedded 53


CycloneTCP User Manual

4.4.14 socketReceiveEx

Syntax
error_t socketReceiveEx(Socket *socket, IpAddr *srcIpAddr,
uint16_t *srcPort, IpAddr *destIpAddr, void *data, size_t size,
size_t *received, uint_t flags)

Parameters
socket Valid handle referencing a socket.

srcIpAddr Optional pointer to a structure that receives the source IP address of the
incoming datagram (can be NULL).

srcPort Optional pointer to a 16-bit integer that receives the source port number
of the incoming datagram (can be NULL).

destIpAddr Optional pointer to a structure that receives the destination IP address of


the incoming datagram (can be NULL).

data Pointer to the buffer where to store the incoming data.

size Maximum number of bytes that can be received.

received Actual number of bytes that have been received.

flags A set of flags that influences the behavior of this function. For most
applications, a value of 0 is recommended.

Return value
The socketReceiveEx function returns NO_ERROR if some data has been successfully
received. Otherwise a non-zero status code describing the error is returned.

Description
The socketReceiveEx function receives a message from a connectionless socket. If no
messages are available in the receive queue, the socket wait for a message to arrive, unless
the socket is non-blocking in which case the function returns immediately. This function is
similar to the socketReceiveFrom function expect that the destination IP address is also
returned.

When the SOCKET_FLAG_PEEK is set, the data is copied into the buffer, but is not
removed from the input queue.

Example
Refer to socketReceiveFrom function

54 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

4.4.15 socketPoll

Syntax
error_t socketPoll(SocketEventDesc *eventDesc, uint_t size,
OsEvent *extEvent, systime_t timeout)

Parameters
eventDesc Set of entries specifying the events the user is interested in.

size Number of entries in the descriptor set.

event External event that can abort the wait if necessary (optional parameter).

timeout Maximum time to wait before returning.

Return value
The socketPoll function returns NO_ERROR if at least one socket is ready to perform I/O.
Otherwise a non-zero status code describing the error is returned.

Description
The socketPoll function waits for one of a set of sockets to become ready to perform I/O. The
eventDesc structure must be initialized prior to function call with desired socket events
(eventMask field). When the function completes, the eventFlags field stores the events that
have been fired for each socket.

The following table lists the events that can be specified in the eventDesc field. Some events
can only be used in conjunction with connection-oriented sockets and are meaningless for
connectionless sockets.

Event Description TCP UDP


SOCKET_EVENT_CONNECTED The connection has been successfully
x
established.
SOCKET_EVENT_CLOSED The connection has been closed. x
SOCKET_EVENT_TX_READY The send buffer is not full. The socket
x
is considered as writable.
SOCKET_EVENT_TX_COMPLETE All the data in the send buffer has
been successfully transmitted and x
acknowledged.
SOCKET_EVENT_TX_SHUTDOWN A FIN segment has been sent and the
x
transmission is now disabled.
SOCKET_EVENT_RX_READY Some data are pending in the receive
buffer. A listening socket has received x x
a connection attempt.
SOCKET_EVENT_RX_SHUTDOWN A FIN segment has been received and
x
the reception is now disabled.
SOCKET_EVENT_LINK_UP The link status of the interface
x x
associated with the socket is up.
SOCKET_EVENT_LINK_DOWN The link status of the interface
x x
associated with the socket is down.

© 2010 - 2019 Oryx Embedded 55


CycloneTCP User Manual

Example
error_t error;
size_t length;
Socket *socket1;
Socket *socket2;
SocketEventDesc eventDesc[2];
uint8_t buffer[256];

//Create two datagram sockets (error processing is omitted for clarity)


socket1 = socketOpen(SOCKET_TYPE_DGRAM, SOCKET_IP_PROTO_UDP);
socket2 = socketOpen(SOCKET_TYPE_DGRAM, SOCKET_IP_PROTO_UDP);

//The first one listens to port 111


error = socketBind(socket1, &IP_ADDR_ANY, 111);
//The second one listens to port 222
error = socketBind(socket2, &IP_ADDR_ANY, 222);

while(1)
{
//Set the events the application is interrested in
eventDesc[0].socket = socket1;
eventDesc[0].eventMask = SOCKET_EVENT_RX_READY;
eventDesc[1].socket = socket2;
eventDesc[1].eventMask = SOCKET_EVENT_RX_READY;

//Wait for incoming datagrams


error = socketPoll(eventDesc, 2, NULL, INFINITE_DELAY);

//Sanity check
if(!error)
{
//Check the state of the first socket
if(eventDesc[0].eventFlags & SOCKET_EVENT_RX_READY)
{
//The receive function should not block since the first
//socket is marked as readable
error = socketReceiveFrom(socket1, NULL, NULL,
buffer, sizeof(buffer), &length, 0);
}
//Check the state of the second socket
if(eventDesc[1].eventFlags & SOCKET_EVENT_RX_READY)
{
//The receive function should not block since the second
//socket is marked as readable
error = socketReceiveFrom(socket2, NULL, NULL,
buffer, sizeof(buffer), &length, 0);
}
}
}

56 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

4.4.16 socketShutdown

Syntax
error_t socketShutdown(Socket *socket, uint_t how)

Parameters
socket Valid handle referencing a socket.

how A flag that describes what types of operation will no longer be allowed.
Possible values are SOCKET_SD_RECEIVE, SOCKET_SD_SEND or
SOCKET_SD_BOTH.

Return value
The socketShutdown function returns NO_ERROR if the operation was successful.
Otherwise a non-zero status code describing the error is returned.

Description
The socketShutdown function is used to disable reception, transmission or both. Call this
function to gracefully disconnect from the remote host. socketShutdown does not close the
socket. Any resources attached to the socket will be not released until socketClose is
invoked.

© 2010 - 2019 Oryx Embedded 57


CycloneTCP User Manual

Example
error_t error;
Socket *serverSocket;
Socket *clientSocket;

//Create a connection-oriented socket


serverSocket = socketOpen(SOCKET_TYPE_STREAM, SOCKET_IP_PROTO_TCP);
//Failed to create socket?
if(!serverSocket) {...}

//Bind the newly created socket to port 17


error = socketBind(serverSocket, &IP_ADDR_ANY, 17);
//Any error to report?
if(error) {...}

//Place socket in listening state


error = socketListen(serverSocket, 0);
//Any error to report?
if(error) {...}

//Endless loop
while(1)
{
//Accept an incoming connection
clientSocket = socketAccept(serverSocket, NULL, NULL);

//Check whether a valid connection request has been received


if(clientSocket)
{
//Send the response to the client
error = socketSend(clientSocket, "Quote of the day", 16, NULL, 0);
//Any error to report?
if(error) {...}

//Gracefully disconnect from the remote host


error = socketShutdown(clientSocket, SOCKET_SD_BOTH);
//Successful shutdown?
if(error) {...}

//Close the socket


socketClose(clientSocket);
}
}

58 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

4.4.17 socketClose

Syntax
void socketClose(Socket *socket)

Parameters
socket Handle identifying the socket to close.

Return value
None.

Description
The socketClose function aborts any running connection and causes the system to release
all the resources allocated to the socket. A closed socket cannot be used for communication
anymore.

© 2010 - 2019 Oryx Embedded 59


CycloneTCP User Manual

Example
error_t error;
size_t length;
char_t buffer[64];
Socket *socket;
IpAddr serverIpAddr;

//Daytime server address


error = ipStringToAddr("192.168.0.100", &serverIpAddr);
//Failed to convert the string to a valid IP address?
if(error) {...}

//Create a connectionless socket


socket = socketOpen(SOCKET_TYPE_DGRAM, SOCKET_IP_PROTO_UDP);
//Failed to create socket?
if(!socket) {...}

//The server listens for UDP datagrams on port 13


error = socketConnect(socket, &serverIpAddr, 13);
//Any error to report?
if(error) {...}

//Send a datagram to the daytime server


error = socketSend(socket, "daytime", 7, NULL, 0);
//Any error to report?
if(error) {...}

//Wait for a response


error = socketReceive(socket, buffer, sizeof(buffer) - 1, &length, 0);
//Timeout error?
if(error) {...}

//Terminate the string with a NULL character


buffer[length] = '\0';

//The response contains the current date and time


printf("Current time: %s\r\n", buffer);

//Properly close the socket


socketClose(socket);

60 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

4.5 BSD Socket API


CycloneTCP also offers a standard socket API that complies with Berkeley sockets.

4.5.1 socket

4.5.2 bind

4.5.3 connect

4.5.4 listen

4.5.5 accept

4.5.6 send

4.5.7 sendto

4.5.8 recv

4.5.9 recvfrom

4.5.10 select

4.5.11 setsockopt

4.5.12 getsockopt

4.5.13 shutdown

4.5.14 close

© 2010 - 2019 Oryx Embedded 61


CycloneTCP User Manual

4.6 Multicast Management
4.6.1 ipJoinMulticastGroup

Syntax
error_t ipJoinMulticastGroup(NetInterface *interface,
const IpAddr *groupAddr)

Parameters
interface Pointer to the network interface on which the multicast group
membership is to be added. This parameter is optional and can be
NULL. In this case the default network interface is used.

groupAddr Pointer to a valid IP address specifying the host group to be joined.

Return value
The ipJoinMulticastGroup function returns NO_ERROR if the specified host group was
successfully joined. Otherwise a non-zero status code describing the error is returned.

Description
The ipJoinMulticastGroup function adds the multicast membership on the specified interface,
if not yet installed. The underlying network interface receives multicast traffic only for the
groups that were previously joined.

Example
error_t error;
IpAddr groupAddr;

//mDNS multicast address is 224.0.0.251 for IPv4


ipStringToAddr("224.0.0.251", &groupAddr);

//Join the mDNS multicast group on the first network interface


error = ipJoinMulticastGroup(&netInterface[0], &groupAddr);
//Failed to add membership?
if(error) {...}

//Leave the mDNS multicast group


ipLeaveMulticastGroup(&netInterface[0], &groupAddr);

62 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

4.6.2 ipLeaveMulticastGroup

Syntax
error_t ipLeaveMulticastGroup(NetInterface *interface,
const IpAddr *groupAddr)

Parameters
interface Pointer to the network interface on which the multicast group
membership must be dropped. This parameter is optional and can be
NULL. In this case the default network interface is used.

groupAddr Pointer to a valid IP address specifying the host group to leave.

Return value
The ipLeaveMulticastGroup function returns NO_ERROR if the specified membership was
successfully dropped. Otherwise a non-zero status code describing the error is returned.

Description
The ipLeaveMulticastGroup function can be called to leave the multicast group identified by
groupAddr on the given network interface. ipLeaveMulticastGroup may succeed, but the
membership persists, if more than one upper-layer protocol has requested membership in
the same group.

Example
error_t error;
IpAddr groupAddr;

//mDNS multicast address is ff02::fb for IPv6 link-local addressing


ipStringToAddr("ff02::fb", &groupAddr);

//Join the mDNS multicast group on the default network interface


error = ipJoinMulticastGroup(NULL, &groupAddr);
//Failed to add membership?
if(error) {...}

//Leave the mDNS multicast group


ipLeaveMulticastGroup(NULL, &groupAddr);

© 2010 - 2019 Oryx Embedded 63


CycloneTCP User Manual

4.7 Host Name Resolution
4.7.1 getHostByName

Syntax
error_t getHostByName(NetInterface *interface, const char_t *name,
IpAddr *ipAddr, uint_t flags)

Parameters
Interface [in] Pointer to the network interface on which the host name resolution
should be performed. This parameter is optional and can be NULL. In
this case the default network interface is used.

name [in] Pointer to the NULL-terminated string containing the host name to be
resolved.

ipAddr [out] IP address corresponding to the specified host name.

Flags [in] A set of flags that influences host name resolution:


 HOST_TYPE_ANY: IPv4 and IPv6 addresses are acceptable
 HOST_TYPE_IPV4: Force IPv4 address resolution
 HOST_TYPE_IPV6: Force IPv6 address resolution
 HOST_NAME_RESOLVER_ANY: Automatic name resolution
 HOST_NAME_RESOLVER_DNS: Use DNS resolver
 HOST_NAME_RESOLVER_MDNS: Use mDNS resolver
 HOST_NAME_RESOLVER_NBNS: Use NetBIOS name service
 HOST_NAME_RESOLVER_LLMNR: Use LLMNR resolver

Return value
The getHostByName function returns NO_ERROR if the host name was successfully
resolved. Otherwise a non-zero status code describing the error is returned.

Description
The getHostByName function translates a given host name to an IP address.

The last parameter serves a guidance to restrict the host name resolution to a limited set of
protocols. If this parameter is zero, the function will automatically select the most appropriate
protocol (DNS, mDNS, NetBIOS name service or LLMNR) to resolve the specified host
name.

64 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

Example
error_t error;
size_t i;
size_t n;
char_t buffer[40];
IpAddr ipAddr;

//Resolve host name using DNS


error = getHostByName(NULL, "www.example.com", &ipAddr,
HOST_TYPE_ANY | HOST_NAME_RESOLVER_ANY):

//Name resolution succeeded?


if(!error)
{
//Display the corresponding IP address
printf("IP address: %s\r\n", ipAddrToString(&ipAddr, buffer));
}
else
{
//Report an error
printf("Host name resolution failed!\r\n");
}

//Resolve host name using mDNS


error = getHostByName(NULL, "example.local", &ipAddr,
HOST_TYPE_ANY | HOST_NAME_RESOLVER_ANY):

//Name resolution succeeded?


if(!error)
{
//Display the corresponding IP address
printf("IP address: %s\r\n", ipAddrToString(&ipAddr, buffer));
}
else
{
//Report an error
printf("Host name resolution failed!\r\n");
}

© 2010 - 2019 Oryx Embedded 65


CycloneTCP User Manual

4.8 Address Conversion
4.8.1 macStringToAddr

Syntax
error_t macStringToAddr(const char_t *str, MacAddr *macAddr)

Parameters
str [in] NULL-terminated string representing the MAC address.

macAddr [out] Pointer to a buffer in which to store the binary representation of the MAC
address.

Return value
The macStringToAddr function returns NO_ERROR if the input string was successfully
converted to a valid MAC address. Otherwise a non-zero status code describing the error is
returned.

Description
The macStringToAddr function converts a string representation of an MAC address into its
binary form. This function is case insensitive and accepts two commonly used formats:
 Six groups of two hexadecimal digits separated by hyphens
 Six groups of two hexadecimal digits separated by colons

Example
error_t error;
MacAddr macAddr;

//Dash-separated hex notation is accepted...


error = macStringToAddr("00-11-22-33-44-55", &macAddr);
error = macStringToAddr("AA-BB-CC-DD-EE-FF", &macAddr);
error = macStringToAddr("aa-bb-cc-dd-ee-ff", &macAddr);

//...as well as colon-separated hex notation


error = macStringToAddr("00:11:22:33:44:55", &macAddr);
error = macStringToAddr("AA:BB:CC:DD:EE:FF", &macAddr);
error = macStringToAddr("aa:bb:cc:dd:ee:ff", &macAddr);

66 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

4.8.2 macAddrToString

Syntax
char_t *macAddrToString(const MacAddr *macAddr, char_t *str)

Parameters
macAddr [in] Binary representation of the MAC address.

str |out] Pointer to a buffer in which to store the text representation of the MAC
address. The buffer must be at least 18-byte long.

Return value
The macAddrToString function returns a pointer to the resulting string.

Description
The macAddrToString function converts a binary MAC address into a human-friendly string
representation. The output string consists of six groups of two hexadecimal digits separated
by hyphens.

Example
To be done

© 2010 - 2019 Oryx Embedded 67


CycloneTCP User Manual

4.8.3 ipStringToAddr

Syntax
error_t ipStringToAddr(const char_t *str, IpAddr *ipAddr)

Parameters
str [in] NULL-terminated string representing the IP address.

ipAddr [out] Pointer to a buffer in which to store the binary representation of the IP
address.

Return value
The ipStringToAddr function returns NO_ERROR if the input string was successfully
converted to a valid IPv4 or IPv6 address. Otherwise a non-zero status code describing the
error is returned.

Description
The ipStringToAddr function converts a string representation of an IP address into its binary
form. The function accepts dot-decimal notation for IPv4 addresses. The conventional text
representations of IPv6 addresses defined in RFC 4291 are supported as well.

Example
error_t error;
IpAddr ipAddr;

//Some valid IPv4 addresses...


error = ipStringToAddr("192.168.0.10", &ipAddr);
error = ipStringToAddr("224.0.0.101", &ipAddr);
error = ipStringToAddr("127.0.0.1", &ipAddr);
error = ipStringToAddr("0.0.0.0", &ipAddr);

//Some valid IPv6 addresses...


error = ipStringToAddr("2001:db8:0:0:8:800:200c:417a", &ipAddr);
error = ipStringToAddr("ff01::101", &ipAddr);
error = ipStringToAddr("::1", &ipAddr);
error = ipStringToAddr("::", &ipAddr);

68 © 2010 - 2019 Oryx Embedded


 CycloneTCP User Manual

4.8.4 ipAddrToString

Syntax
char_t *ipAddrToString(const IpAddr *ipAddr, char_t *str)

Parameters
ipAddr [in] Binary representation of the IP address.

str |out] Pointer to a buffer in which to store the text representation of the IP
address. The buffer must be at least 16-byte long for IPv4 addresses and
40-byte long for IPv6.

Return value
The ipAddrToString function returns a pointer to the resulting string.

Description
The ipAddrToString function converts a binary IP address into a human-friendly string
representation. IPv4 addresses are converted to dot-decimal form. ipAddrToString formats
IPv6 addresses according to RFC 5952 recommendations.

Example
error_t error;
char_t buffer[40];
IpAddr ipAddr;

//Resolve host name


error = getHostByName(NULL, "www.example.com", &ipAddr, 1, NULL, 0):

//Name resolution succeeded?


if(!error)
{
//Display resulting IP address
printf("IP address: %s\r\n", ipAddrToString(&ipAddr, buffer));
}
else
{
//Report an error
printf("Host name resolution failed!\r\n");
}

© 2010 - 2019 Oryx Embedded 69

S-ar putea să vă placă și