NetBurner 3.5.6
PDF Version |
TCP socket programming interface. More...
Topics | |
TCP Notification System | |
Advanced callback mechanism for asynchronous TCP socket event notification. | |
TCP Socket Options | |
Configuration flags for TCP socket behavior. | |
TCP Socket State | |
TCP connection state machine values (RFC 793) | |
TCP Socket Status | |
Status codes and error values for TCP socket operations. | |
Functions | |
int | accept (int listening_socket, IPADDR *address, uint16_t *port, uint16_t timeout) |
Accept an incoming connection on a listening socket. | |
int | accept (int listening_socket, IPADDR *address, uint16_t *port, TickTimeout &timeout) |
Accept an incoming connection on a listening socket with timeout object. | |
int | connect (const IPADDR &ipAddress, uint16_t remotePort, uint32_t timeout) |
Establish a TCP connection to a remote host. | |
int | connectvia (const IPADDR &ipAddress, uint16_t remotePort, uint32_t timeout, const IPADDR &localIpAddress) |
Establish a TCP connection using a specific local interface IP address. | |
int | connectvia (const IPADDR &ipAddress, uint16_t remotePort, uint32_t timeout, int ifnum) |
Establish a TCP connection using a specific local interface number. | |
int | connectwlocal (const IPADDR &ipAddress, uint16_t localPort, uint16_t remotePort, uint32_t timeout, const IPADDR &localIpAddress=IPADDR::NullIP(), int intf=-1) |
Establish a TCP connection with full control over local parameters. | |
int | connect (const IPADDR &ipAddress, uint16_t remotePort, TickTimeout &timeout) |
Establish a TCP connection to a remote host with TickTimeout object. | |
int | connectvia (const IPADDR &ipAddress, uint16_t remotePort, TickTimeout &timeout, const IPADDR &localIpAddress) |
Establish a TCP connection using a specific local interface IP with TickTimeout. | |
int | connectvia (const IPADDR &ipAddress, uint16_t remotePort, TickTimeout &timeout, int ifnum) |
Establish a TCP connection using a specific local interface number with TickTimeout. | |
int | connectwlocal (const IPADDR &ipAddress, uint16_t localPort, uint16_t remotePort, TickTimeout timeout, const IPADDR &localIpAddress=IPADDR::NullIP(), int intf=-1) |
Establish a TCP connection with full control over local parameters and TickTimeout. | |
int | listen (const IPADDR &addr, uint16_t port, uint8_t maxpend=5) |
Create a listening socket to accept incoming TCP connections. | |
int | listenvia (const IPADDR &addr, uint16_t port, int ifn, uint8_t maxpend=5) |
Create a listening socket on a specific network interface. | |
int | listenvia (const IPADDR &addr, uint16_t port, const IPADDR &localIpAddress, uint8_t maxpend=5) |
Create a listening socket bound to a specific interface IP address. | |
int | NoBlockConnect (const IPADDR &ipAddress, uint16_t remotePort) |
Initiate a non-blocking TCP connection. | |
int | NoBlockConnectVia (const IPADDR &ipAddress, uint16_t remotePort, const IPADDR &interfaceIpAddress=IPADDR::NullIP()) |
Initiate a non-blocking TCP connection via a specific interface. | |
int | NoBlockConnectVia (const IPADDR &ipAddress, uint16_t remotePort, int ifnum) |
Initiate a non-blocking TCP connection via a specific interface number. | |
int | NoBlockConnectwlocal (const IPADDR &ipAddress, uint16_t localPort, uint16_t remotePort, IPADDR interfaceIpAddress=IPADDR::NullIP(), int ifn=-1) |
Initiate a non-blocking TCP connection with full local parameter control. | |
int | getsocketerror (int fd) |
Get the error status of a socket. | |
IPADDR | GetSocketRemoteAddr (int fd) |
Get the remote host IP address for a socket connection. | |
IPADDR | GetSocketLocalAddr (int fd) |
Get the local interface IP address for a socket connection. | |
uint16_t | GetSocketRemotePort (int fd) |
Get the remote host port number for a socket connection. | |
uint16_t | GetSocketLocalPort (int fd) |
Get the local port number for a socket connection. | |
uint32_t | TcpGetLastRxTime (int fd) |
Get the system tick count when the last packet was received. | |
void | TcpSendKeepAlive (int fd) |
Send a TCP keepalive probe packet. | |
uint32_t | TcpGetLastRxInterval (int fd) |
Get the time elapsed since the last received packet. | |
int | GetTcpRtxCount (int fd) |
Get the number of TCP retransmissions on a socket. | |
uint8_t | SetOutOfOrderBuffers (int fd, uint8_t max) |
Configure the maximum number of out-of-order buffers for a TCP socket. | |
int | setsockoption (int fd, int option) |
Enable TCP socket options. | |
int | clrsockoption (int fd, int option) |
Disable TCP socket options. | |
int | getsockoption (int fd) |
Query current TCP socket options. | |
int | SetSocketUnackBuffers (int fd, uint8_t val) |
Configure the maximum number of unacknowledged transmit buffers. | |
int | SetSocketRxBuffers (int fd, int n) |
Configure the number of TCP receive buffers. | |
int | SetSocketTxBuffers (int fd, int n) |
Configure the number of TCP transmit buffers. | |
int | abortsocket (int fd) |
Abort a TCP connection immediately. | |
int | SockReadWithTimeout (int fd, char *buf, int nbytes, uint32_t timeout) |
Read from a TCP socket with a timeout. | |
char | SocketPeek (int fd) |
Peek at the next available byte without removing it from the receive buffer. | |
void | DumpTcpDebug () |
Display current TCP debug information to the console. | |
void | EnableTcpDebug (uint16_t dbFlags) |
Enable TCP debug output with specified flags. | |
int | TcpGetSocketInterface (int fd) |
Get the network interface number associated with a TCP socket. | |
uint8_t | TcpGetSocketState (int fd) |
Get the current TCP state of a socket. | |
uint16_t | TcpGetRxBufferSpaceUsed (int fd) |
Get the number of bytes currently in the receive buffer. | |
uint16_t | TcpGetTxBufferAvailSpace (int fd) |
Get the available space in the transmit buffer. | |
uint16_t | TcpGetTxDataWaiting (int fd) |
Get the number of bytes queued for transmission. | |
BOOL | TcpAllDataAcked (int socket) |
Check if all transmitted data has been acknowledged. | |
BOOL | WaitForSocketFlush (int fd, uint32_t ticks) |
Wait for all transmitted data to be acknowledged. | |
TCP socket programming interface.
#include< tcp.h>
The NetBurner TCP API provides a robust, Berkeley-sockets-style interface for TCP/IP networking with support for both blocking and non-blocking operations. This API is designed specifically for embedded systems and real-time applications, offering fine-grained control over socket behavior, buffer management, and connection state.
Key Features:
The TCP API supports three primary usage patterns:
Create a listening socket to accept incoming client connections:
Establish an outbound connection to a remote server:
For applications requiring immediate return without waiting:
NetBurner applications start in UserMain(), not main(). Always call init() at the beginning of UserMain() to initialize the network stack before using TCP functions.
Many functions accept timeout parameters in system ticks. Use the TICKS_PER_SECOND constant for conversion:
TICKS_PER_SECOND * 5
TICKS_PER_SECOND * 30
0
TCP sockets are represented by integer file descriptors (fd). Functions that create sockets (listen(), accept(), connect()) return:
Always check return values:
TCP sockets use system buffer pools for transmit and receive operations. The default buffer allocation is conservative (5 buffers per socket) to support many simultaneous connections. For high-throughput applications, you can increase buffer allocations:
TCP connections progress through well-defined states (RFC 793). Use TcpGetSocketState() to query the current state:
Always call close() on sockets when finished to free system resources. This applies even if the socket enters an error state or TCP_STATE_CLOSING. Failing to close sockets will leak file descriptors and network buffers.
#define TCP_THROUGHPUT_INFO
)TCP functions use negative return values to indicate errors. Always check return values and handle errors appropriately:
Common error codes (see TCP Socket Status):
For detailed return code information, causes and solutions, see: Programmers Guide TCP Error Codes
When multiple network interfaces are available, you can control which interface is used for connections:
connectvia(addr, port, timeout, localIpAddress)
: Use interface with specific IPconnectvia(addr, port, timeout, ifnum)
: Use interface by numberDetect stale connections using the keepalive mechanism:
The Nagle algorithm buffers small packets to improve efficiency but can add latency for interactive applications. Use SO_NONAGLE option to disable:
For event-driven architectures, register notification callbacks instead of polling:
The TCP API conditionally compiles for IPv4-only (IPV4ONLY) or dual-stack IPv6 support. When IPv6 is enabled:
For maximum throughput when transferring large amounts of data:
SetSocketRxBuffers(fd, 43)
// Maximum effectiveSetSocketTxBuffers(fd, 20)
SetSocketUnackBuffers(fd, 20)
setsockoption(fd, SO_NONAGLE)
For interactive or real-time applications requiring minimal latency:
setsockoption(fd, SO_NONAGLE)
For servers handling many concurrent connections:
The NetBurner TCP implementation is designed for use in a multi-threaded RTOS environment. However, individual socket operations are not automatically thread-safe:
The TCP API works in conjunction with other NetBurner APIs:
int abortsocket | ( | int | fd | ) |
#include <tcp.h>
Abort a TCP connection immediately.
Forcefully terminates a TCP connection by sending a RST (reset) packet to the remote host. Unlike a normal close(), this does not perform a graceful shutdown and any pending data will be lost. Use this only when you need to terminate a connection immediately without the normal shutdown handshake.
fd | Socket file descriptor |
Expand for Example Usage
int accept | ( | int | listening_socket, |
IPADDR * | address, | ||
uint16_t * | port, | ||
TickTimeout & | timeout ) |
#include <tcp.h>
Accept an incoming connection on a listening socket with timeout object.
Accepts a pending connection request from the listen queue using a TickTimeout object for more flexible timeout management. The listening socket must have been created with listen() before calling this function. Each successful accept frees one slot in the listen queue for additional incoming connections.
This overload of accept() uses a TickTimeout object instead of a simple tick count, providing more sophisticated timeout behavior. The TickTimeout object can track elapsed time across multiple operations and provides precise timeout management for complex scenarios.
listening_socket | File descriptor of the listening socket (obtained from listen()) |
address | Pointer to IPADDR to store the remote client's IP address. Pass NULL if you don't need the client's IP address |
port | Pointer to uint16_t to store the remote client's port number. Pass NULL if you don't need the client's port |
timeout | Reference to TickTimeout object specifying the maximum wait time. The TickTimeout tracks elapsed time and can be reused across multiple operations. Create with TickTimeout(ticks) where ticks is the total timeout period in system ticks |
Notes:
Expand for Example Usage
int accept | ( | int | listening_socket, |
IPADDR * | address, | ||
uint16_t * | port, | ||
uint16_t | timeout ) |
#include <tcp.h>
Accept an incoming connection on a listening socket.
Accepts a pending connection request from the listen queue. The listening socket must have been created with listen() before calling this function. Each successful accept frees one slot in the listen queue for additional incoming connections.
This function blocks until either a connection arrives or the timeout expires. When a client connects, accept() returns a new socket file descriptor for communicating with that specific client. The original listening socket remains open and continues to accept new connections.
listening_socket | File descriptor of the listening socket (obtained from listen()) |
address | Pointer to IPADDR to store the remote client's IP address. Pass NULL if you don't need the client's IP address |
port | Pointer to uint16_t to store the remote client's port number. Pass NULL if you don't need the client's port |
timeout | Maximum wait time in system ticks:
|
Notes:
Expand for Example Usage
int clrsockoption | ( | int | fd, |
int | option ) |
#include <tcp.h>
Disable TCP socket options.
Clears one or more option flags for the specified socket. Socket options control various aspects of TCP behavior such as the Nagle algorithm and PUSH flag handling. Multiple options can be combined using bitwise OR.
fd | Socket file descriptor |
option | Socket option flags to disable: TCP Socket Options |
Notes:
clrsockoption(fd, SO_NODELAY | SO_PUSH);
Expand for Example Usage
|
inline |
#include <tcp.h>
Establish a TCP connection to a remote host with TickTimeout object.
Creates a new TCP socket and attempts to connect to the specified remote IP address and port using a TickTimeout object for timeout management. This overload provides more sophisticated timeout tracking compared to the simple tick count version, allowing the timeout to be shared across multiple operations and providing precise elapsed time tracking.
The function automatically selects the local interface based on the routing table and assigns an available local port. The TickTimeout object is updated to reflect the remaining time after the connection attempt, enabling accurate timeout management across sequential operations.
ipAddress | IP address of the remote host. Can be created using AsciiToIp() or obtained from DNS resolution. Example: AsciiToIp("192.168.1.100") |
remotePort | Port number on the remote host (1-65535). Common ports include:
|
timeout | Reference to TickTimeout object specifying the maximum wait time. The TickTimeout tracks elapsed time and can be reused across multiple operations. Create with TickTimeout(ticks) where ticks is the total timeout period in system ticks. The object is updated by this function to reflect remaining time |
Notes:
Expand for Example Usage
|
inline |
#include <tcp.h>
Establish a TCP connection to a remote host.
Creates a new TCP socket and attempts to connect to the specified remote IP address and port. This is a blocking call that waits up to the specified timeout period for the connection to be established. The function automatically selects the local interface based on the routing table and assigns an available local port.
This is the most commonly used function for establishing outbound TCP connections. The operating system automatically selects the appropriate local interface and port number based on the destination address and routing configuration.
ipAddress | IP address of the remote host. Can be created using AsciiToIp() or obtained from DNS resolution. Example: AsciiToIp("192.168.1.100") |
remotePort | Port number on the remote host (1-65535). Common ports include:
|
timeout | Maximum connection time in system ticks. Use TICKS_PER_SECOND macro:
|
Notes:
Expand for Example Usage
|
inline |
#include <tcp.h>
Establish a TCP connection using a specific local interface IP with TickTimeout.
Creates a new TCP socket and connects to the remote host using the specified local network interface identified by its IP address, with TickTimeout object for sophisticated timeout management. This combines the benefits of explicit interface selection with precise timeout tracking across multiple operations.
This function is ideal for multi-homed systems where you need both controlled interface selection and the ability to share timeout budgets across sequential operations. The TickTimeout object is updated to reflect remaining time, enabling accurate timeout management for complex connection sequences.
ipAddress | IP address of the remote host. Can be IPv4 or IPv6 depending on build configuration |
remotePort | Port number on the remote host (1-65535) |
timeout | Reference to TickTimeout object specifying the maximum wait time. The TickTimeout tracks elapsed time and can be reused across multiple operations. The object is updated by this function to reflect remaining time after the connection attempt |
localIpAddress | IP address of the local interface to use for this connection. The system will select the network interface that has this IP address assigned. Use IPADDR::NullIP() to fall back to automatic interface selection based on routing table |
Notes:
-is function blocks the calling task until the connection is established or the timeout expires. For non-blocking connection attempts, use NoBlockConnectVia().
Expand for Example Usage
|
inline |
#include <tcp.h>
Establish a TCP connection using a specific local interface number with TickTimeout.
Creates a new TCP socket and connects to the remote host using the specified local network interface number, with TickTimeout object for sophisticated timeout management. This provides the most direct interface control combined with precise timeout tracking, ideal for complex multi-homed systems requiring both explicit interface selection and accurate time budget management.
This function combines the unambiguous interface control of interface number selection with the advanced timeout capabilities of TickTimeout. The interface number takes precedence over all routing decisions, and the TickTimeout object tracks elapsed time for sharing timeout budgets across sequential operations.
ipAddress | IP address of the remote host. Can be IPv4 or IPv6 depending on build configuration |
remotePort | Port number on the remote host (1-65535) |
timeout | Reference to TickTimeout object specifying the maximum wait time. The TickTimeout tracks elapsed time and can be reused across multiple operations. The object is updated by this function to reflect remaining time after the connection attempt |
ifnum | Local interface number (0, 1, 2, etc.) to use for this connection. This overrides all routing decisions based on destination IP addresses. The interface number directly corresponds to the physical or logical network interface. Valid range is 0 to (number of interfaces - 1). Use GetNumberOfInterfaces() to determine valid range |
Notes:
Expand for Example Usage
|
inline |
#include <tcp.h>
Establish a TCP connection using a specific local interface IP address.
Creates a new TCP socket and connects to the remote host using the specified local network interface identified by its IP address. This allows control over which interface is used when multiple network interfaces are available. The standard connect() function uses the default interface selected by the routing table, while this function overrides that decision.
This is particularly useful in multi-homed systems where you need to ensure traffic uses a specific network path, such as separating control and data traffic, routing through different network segments, or implementing failover between interfaces.
ipAddress | IP address of the remote host. Can be IPv4 or IPv6 depending on build configuration |
remotePort | Port number on the remote host (1-65535) |
timeout | Maximum connection time in system ticks:
|
localIpAddress | IP address of the local interface to use for this connection. The system will select the network interface that has this IP address assigned. If multiple interfaces share the same IP (unusual configuration), the lower numbered interface is selected. Use IPADDR::NullIP() to fall back to automatic interface selection based on routing table (equivalent to calling connect()) |
Notes:
Expand for Example Usage
|
inline |
#include <tcp.h>
Establish a TCP connection using a specific local interface number.
Creates a new TCP socket and connects to the remote host using the specified local network interface number. This allows direct control over which interface is used, completely overriding the routing table. The interface number takes precedence over any IP-based routing decisions, providing the most explicit control over interface selection.
This is the most direct way to control interface selection in multi-homed systems. Unlike selecting by IP address, specifying an interface number eliminates any ambiguity about which interface will be used, even if multiple interfaces share similar IP configurations.
ipAddress | IP address of the remote host. Can be IPv4 or IPv6 depending on build configuration |
remotePort | Port number on the remote host (1-65535) |
timeout | Maximum connection time in system ticks:
|
ifnum | Local interface number (0, 1, 2, etc.) to use for this connection. This overrides all routing decisions based on destination IP addresses. The interface number directly corresponds to the physical or logical network interface. Valid range is 0 to (number of interfaces - 1). Use GetNumberOfInterfaces() to determine valid range |
Notes:
Expand for Example Usage
|
inline |
#include <tcp.h>
Establish a TCP connection with full control over local parameters and TickTimeout.
Creates a new TCP socket with complete control over both local and remote connection parameters, using a TickTimeout object for sophisticated timeout management. This function allows specification of the local port, interface IP address, or interface number, combined with precise timeout tracking for complex connection sequences.
This is the most advanced connection function, providing maximum control over all connection parameters plus the ability to track elapsed time and share timeout budgets. Most applications should use simpler connection functions unless they have specific requirements for local port control, explicit interface selection, and advanced timeout management.
ipAddress | IP address of the remote host. Can be IPv4 or IPv6 depending on build configuration |
localPort | Local port number to bind (1-65535, or 0 for automatic assignment). Strongly recommend using 0 unless you have a specific protocol requirement (e.g., FTP active mode). Non-zero values can cause TCP_ERR_NOCON or connection failures when reconnecting if the previous connection is in TIME_WAIT state on the remote side |
remotePort | Port number on the remote host (1-65535) |
timeout | TickTimeout object specifying the maximum wait time. Unlike the reference version, this is passed by value, so the original timeout object is not modified. The function creates an internal copy for timeout tracking |
localIpAddress | IP address of the local interface to use. Selects the network interface with this IP address. Use IPADDR::NullIP() if you want to specify interface by number instead (intf parameter). Default: IPADDR::NullIP() (automatic selection or use intf) |
intf | Local interface number (0, 1, 2, etc.). Use -1 if you want to specify interface by IP address instead (localIpAddress parameter). Interface number takes precedence over IP-based routing. Default: -1 (use IP-based routing or localIpAddress) |
Notes:
Expand for Example Usage
|
inline |
#include <tcp.h>
Establish a TCP connection with full control over local parameters.
Creates a new TCP socket with complete control over both local and remote connection parameters. This function allows specification of the local port, interface IP address, or interface number. This is an advanced function intended for specialized use cases where standard connect() or connectvia() are insufficient.
Most applications should use connect() or connectvia() instead. This function is provided for protocols or scenarios that require specific local port numbers or explicit control over both the interface and local port simultaneously.
ipAddress | IP address of the remote host. Can be IPv4 or IPv6 depending on build configuration |
localPort | Local port number to bind (1-65535, or 0 for automatic assignment). Strongly recommend using 0 unless you have a specific protocol requirement. Non-zero values can cause TCP_ERR_NOCON or connection failures when reconnecting if the previous connection is in TIME_WAIT state on the remote side |
remotePort | Port number on the remote host (1-65535) |
timeout | Maximum connection time in system ticks:
|
localIpAddress | IP address of the local interface to use. Selects the network interface with this IP address. Use IPADDR::NullIP() if you want to specify interface by number instead (intf parameter). Default: IPADDR::NullIP() (automatic selection) |
intf | Local interface number (0, 1, 2, etc.). Use -1 if you want to specify interface by IP address instead (localIpAddress parameter). Interface number takes precedence over IP-based routing. Default: -1 (use IP-based routing or localIpAddress) |
Notes:
Parameter Priority:
Local Port Behavior:
Common Use Cases:
Always call close() on the returned file descriptor when finished to free system resources and release the local port.
Expand for Example Usage
void DumpTcpDebug | ( | ) |
#include <tcp.h>
Display current TCP debug information to the console.
Outputs detailed TCP debug information to the console, including active connections, socket states, buffer usage, and other TCP stack diagnostics. The information displayed depends on which debug flags have been enabled via EnableTcpDebug(). This function is useful for troubleshooting network issues and monitoring TCP connection states.
Expand for Example Usage
void EnableTcpDebug | ( | uint16_t | dbFlags | ) |
#include <tcp.h>
Enable TCP debug output with specified flags.
Configures which types of TCP debug information should be tracked and displayed when DumpTcpDebug() is called. The debug flags control the level of detail and which aspects of TCP operations are monitored. Use bitwise OR to combine multiple flags. Set to 0 to disable all TCP debugging.
dbFlags | Debug flags to enable (bitwise OR of debug flag values)
|
Expand for Example Usage
int getsocketerror | ( | int | fd | ) |
#include <tcp.h>
Get the error status of a socket.
Retrieves the current error state of a socket file descriptor. This function is useful for diagnosing connection failures, especially with non-blocking sockets where errors may not be immediately apparent from the return value of connect() or other operations.
fd | File descriptor of the socket to query |
Notes:
Expand for Example Usage
|
inline |
#include <tcp.h>
Get the local interface IP address for a socket connection.
Retrieves the IP address of the local network interface used for the specified socket connection. This function works for both client connections and server sockets that have accepted a connection.
fd | Socket file descriptor |
Notes: For listening sockets, this returns the address the socket is bound to. If bound to INADDR_ANY, it returns INADDR_ANY rather than a specific interface IP.
Expand for Example Usage
uint16_t GetSocketLocalPort | ( | int | fd | ) |
#include <tcp.h>
Get the local port number for a socket connection.
Retrieves the local port number assigned to the specified socket connection.
fd | Socket file descriptor |
|
inline |
#include <tcp.h>
Get the remote host IP address for a socket connection.
Retrieves the IP address of the remote host connected to the specified socket. This function works for both established connections and listening sockets that have accepted a client connection.
fd | Socket file descriptor |
Notes:
Expand for Example Usage
uint16_t GetSocketRemotePort | ( | int | fd | ) |
#include <tcp.h>
Get the remote host port number for a socket connection.
Retrieves the port number being used by the remote host in the specified socket connection. This function works for both client connections and server sockets that have accepted a connection.
fd | Socket file descriptor |
Notes:
Expand for Example Usage
int getsockoption | ( | int | fd | ) |
#include <tcp.h>
Query current TCP socket options.
Retrieves the currently enabled option flags for the specified socket. The return value is a bitmask where each set bit represents an enabled option.
fd | Socket file descriptor |
Notes:
if (getsockoption(fd) & SO_NODELAY) { ... }
Expand for Example Usage
int GetTcpRtxCount | ( | int | fd | ) |
#include <tcp.h>
Get the number of TCP retransmissions on a socket.
Returns the count of how many times TCP has retransmitted data on this connection. Retransmissions occur when acknowledgments are not received from the remote host within the expected timeout period. A high retransmission count may indicate network congestion, packet loss, or a slow/unstable connection.
fd | Socket file descriptor |
Notes:
Expand for Example Usage
|
inline |
#include <tcp.h>
Create a listening socket to accept incoming TCP connections.
Creates a socket that listens for incoming connection requests on the specified port. This is the server-side counterpart to connect(), enabling your application to accept connections from remote clients. Incoming connections are placed in a pending queue until accepted with accept(). The maxpend parameter determines how many connections can wait in the queue before new connection attempts are rejected by the TCP stack.
The listening socket itself does not handle data transfer - it only accepts new connections. Each accepted connection returns a new socket file descriptor for communicating with that specific client. The listening socket remains open and continues accepting new connections.
addr | IP address to bind to:
|
port | Port number to listen on (1-65535). Common server ports include:
|
maxpend | Maximum number of pending connections in the accept queue (default: 5). This is the maximum number of clients that can be waiting in the queue simultaneously. When this limit is reached, additional connection attempts will be refused by the TCP stack. Typical values are 5-20. Higher values consume more system resources but allow for burst connection handling |
Notes:
Expand for Example Usage
|
inline |
#include <tcp.h>
Create a listening socket bound to a specific interface IP address.
Creates a socket that listens for incoming connection requests on the specified port using the network interface with the given IP address. If multiple interfaces share the same IP address, the lower numbered interface is selected. Incoming connections are placed in a pending queue until accepted with accept().
addr | IP address to bind to (use INADDR_ANY to accept connections on any interface) |
port | Port number to listen on |
localIpAddress | IP address of the local interface to use. Selects the interface with this IP address (lower numbered interface if multiple match) |
maxpend | Maximum number of pending connections in the accept queue (default: 5) |
Expand for Example Usage
|
inline |
#include <tcp.h>
Create a listening socket on a specific network interface.
Creates a socket that listens for incoming connection requests on the specified port and network interface. This provides direct control over which interface accepts connections when multiple interfaces are available, useful in multi-homed systems where you need to segregate traffic by interface or ensure connections arrive on a specific network path.
This function is the interface-specific version of listen(). While listen() accepts connections on all interfaces (when using INADDR_ANY) or relies on IP routing, this function gives explicit control by interface number. Incoming connections are placed in a pending queue until accepted with accept().
addr | IP address to bind to:
|
port | Port number to listen on (1-65535). The port must not already be in use on any interface |
ifn | Network interface number (0, 1, 2, etc.) to bind to. This forces the listening socket to accept connections only through this specific interface, regardless of routing table or IP address configuration. Valid range is 0 to (number of interfaces - 1). Use GetNumberOfInterfaces() to determine valid range |
maxpend | Maximum number of pending connections in the accept queue (default: 5). This is the maximum number of clients that can be waiting simultaneously. When this limit is reached, additional connection attempts will be refused |
Notes
Expand for Example Usage
|
inline |
#include <tcp.h>
Initiate a non-blocking TCP connection.
Creates a TCP socket and initiates a connection to the remote host, returning immediately without waiting for the connection to complete. The application must poll the socket state using TcpGetSocketState() to determine when the connection is established (TCP_STATE_ESTABLISHED). The connection status can also be checked using writeavail().
ipAddress | IP address of the remote host |
remotePort | Port number on the remote host |
Notes:
Expand for Example Usage
|
inline |
#include <tcp.h>
Initiate a non-blocking TCP connection via a specific interface.
Creates a TCP socket and initiates a connection to the remote host using the specified local interface IP address. The function returns immediately without waiting for the connection to complete. The application must poll the socket state using TcpGetSocketState() to determine when the connection is established (TCP_STATE_ESTABLISHED).
ipAddress | IP address of the remote host |
remotePort | Port number on the remote host |
interfaceIpAddress | IP address of the local interface to use (default: IPADDR::NullIP() for automatic selection based on routing) |
|
inline |
#include <tcp.h>
Initiate a non-blocking TCP connection via a specific interface number.
Creates a TCP socket and initiates a connection to the remote host using the specified local interface number. The function returns immediately without waiting for the connection to complete. The interface number overrides routing decisions based on destination IP address. The application must poll the socket state using TcpGetSocketState() to determine when the connection is established (TCP_STATE_ESTABLISHED).
ipAddress | IP address of the remote host |
remotePort | Port number on the remote host |
ifnum | Network interface number to use. Overrides all routing decisions |
Notes:
Expand for Example Usage
|
inline |
#include <tcp.h>
Initiate a non-blocking TCP connection with full local parameter control.
Creates a TCP socket with complete control over connection parameters and initiates a connection to the remote host. The function returns immediately without waiting for the connection to complete. The application must poll the socket state using TcpGetSocketState() to determine when the connection is established (TCP_STATE_ESTABLISHED).
ipAddress | IP address of the remote host |
localPort | Local port number to bind (recommend 0 for automatic assignment). Warning: Non-zero values can cause connection failures with half-open sockets on the remote side |
remotePort | Port number on the remote host |
interfaceIpAddress | IP address of local interface (use IPADDR::NullIP() if using ifn) |
ifn | Network interface number (use -1 if using interfaceIpAddress) |
Notes: This function provides the most control over connection parameters but is rarely needed. For most applications, use NoBlockConnect() or NoBlockConnectVia() instead.
Expand for Example Usage
|
inline |
#include <tcp.h>
Configure the maximum number of out-of-order buffers for a TCP socket.
Sets the maximum number of out-of-order TCP receive buffers for the socket. TCP may receive packets out of sequence, which must be stored until earlier packets arrive to maintain correct data ordering. Each buffer is approximately 1500 bytes.
The default value is 5 buffers. The maximum is 43 buffers. Increasing this value can improve bulk data throughput on fast networks but may increase TCP latency if connection problems (such as resets) occur.
fd | Socket file descriptor |
max | Maximum number of out-of-order buffers (1-43, default: 5) |
Notes:
Expand for Example Usage
int SetSocketRxBuffers | ( | int | fd, |
int | n ) |
#include <tcp.h>
Configure the number of TCP receive buffers.
Sets the maximum number of receive buffers allocated to the socket. Each buffer is approximately 1548 bytes. The available space in these buffers determines the TCP window size advertised to the remote host, which controls how much data they can send.
As data is read from the socket, buffer space is freed, allowing the remote host to send more data. Since the maximum TCP window size is 65536 bytes, increasing this value beyond 43 buffers (approximately 66KB) provides no additional benefit.
The system default is 5 buffers (defined in constants.h) to conserve network buffer resources. This default is sufficient for most applications unless transferring large amounts of bulk data.
fd | Socket file descriptor |
n | Number of receive buffers to allocate |
Expand for Example Usage
int SetSocketTxBuffers | ( | int | fd, |
int | n ) |
#include <tcp.h>
Configure the number of TCP transmit buffers.
Sets the maximum number of buffers allocated to the transmit queue. Each buffer is approximately 1548 bytes. The transmit queue accumulates outgoing data up to this limit regardless of the current state of unacknowledged buffers or the remote host's window size. This value effectively sets the maximum size for a single write() operation.
fd | Socket file descriptor |
n | Number of transmit buffers to allocate |
Expand for Example Usage
|
inline |
#include <tcp.h>
Configure the maximum number of unacknowledged transmit buffers.
Sets the maximum number of TCP transmit buffers that can remain unacknowledged by the remote host. When data is sent, it moves from the transmit queue to the unacknowledged list. Buffers remain in this list until the remote host sends an acknowledgment (ACK), at which point they are freed. The actual number of unacknowledged buffers is also limited by the remote host's TCP window size.
Increasing this value can improve bulk data throughput on fast networks. However, on lossy networks without selective acknowledgment (SACK), higher values may reduce performance. Note: Most modern PCs support SACK, but many NAT routers do not.
fd | Socket file descriptor |
val | Maximum number of unacknowledged buffers |
Expand for Example Usage
int setsockoption | ( | int | fd, |
int | option ) |
#include <tcp.h>
Enable TCP socket options.
Sets one or more option flags for the specified socket. Socket options control various aspects of TCP behavior such as the Nagle algorithm and PUSH flag handling. Multiple options can be combined using bitwise OR.
fd | Socket file descriptor |
option | Socket option flags to enable: TCP Socket Options |
Notes:
setsockoption(fd, SO_NODELAY | SO_PUSH);
Expand for Example Usage
char SocketPeek | ( | int | fd | ) |
#include <tcp.h>
Peek at the next available byte without removing it from the receive buffer.
Examines the next byte that would be read from the socket without actually removing it from the receive buffer. The byte remains available for subsequent read operations. If no data is available, returns 0.
fd | Socket file descriptor |
Expand for Example Usage
int SockReadWithTimeout | ( | int | fd, |
char * | buf, | ||
int | nbytes, | ||
uint32_t | timeout ) |
#include <tcp.h>
Read from a TCP socket with a timeout.
Attempts to read data from a TCP socket, waiting up to the specified timeout period. The function returns when at least 1 byte of data becomes available or the timeout expires. The nbytes parameter specifies the maximum number of bytes to read, but the actual number read may be less. Always check the return value to determine how many bytes were actually read.
fd | Socket file descriptor |
buf | Buffer to store received data |
nbytes | Maximum number of bytes to read |
timeout | Timeout duration in system ticks. Recommended usage: TICKS_PER_SECOND * n where n is the number of seconds. For example: TICKS_PER_SECOND * 5 for a 5 second timeout |
Expand for Example Usage
BOOL TcpAllDataAcked | ( | int | socket | ) |
#include <tcp.h>
Check if all transmitted data has been acknowledged.
Determines whether all data sent on this socket has been acknowledged by the remote host. This is useful for ensuring data has been successfully delivered before closing a connection or performing other operations.
socket | Socket file descriptor |
TRUE | All sent data has been acknowledged by the remote host |
FALSE | Some data remains unacknowledged |
uint32_t TcpGetLastRxInterval | ( | int | fd | ) |
#include <tcp.h>
Get the time elapsed since the last received packet.
Calculates the number of system ticks that have elapsed between the current time and when the last packet was received on this socket. This is a convenience function that computes the difference between the current system time (TimeTick) and the socket's lastRxTime value.
fd | Socket file descriptor |
Notes:
uint32_t seconds = TcpGetLastRxInterval(fd) / TICKS_PER_SECOND;
Expand for Example Usage
uint32_t TcpGetLastRxTime | ( | int | fd | ) |
#include <tcp.h>
Get the system tick count when the last packet was received.
Returns the timestamp (in system ticks) of the last received packet on this connection. Each TCP socket maintains a lastRxTime value that is updated whenever a packet arrives. This function is primarily used with TcpSendKeepAlive() to implement TCP keepalive functionality and detect stale connections.
To detect a lost connection:
fd | Socket file descriptor |
Notes:
Expand for Example Usage
uint16_t TcpGetRxBufferSpaceUsed | ( | int | fd | ) |
#include <tcp.h>
Get the number of bytes currently in the receive buffer.
Returns the amount of received data waiting to be read from the socket's receive buffer.
fd | Socket file descriptor |
int TcpGetSocketInterface | ( | int | fd | ) |
#include <tcp.h>
Get the network interface number associated with a TCP socket.
Retrieves the network interface number being used by an established TCP connection.
fd | Socket file descriptor |
Expand for Example Usage
uint8_t TcpGetSocketState | ( | int | fd | ) |
#include <tcp.h>
Get the current TCP state of a socket.
Queries the current state of a TCP socket connection. The returned value corresponds to one of the states in the TCP state machine as defined in RFC 793.
fd | Socket file descriptor |
uint16_t TcpGetTxBufferAvailSpace | ( | int | fd | ) |
#include <tcp.h>
Get the available space in the transmit buffer.
Returns the number of bytes that can be written to the socket's transmit buffer before it becomes full.
fd | Socket file descriptor |
uint16_t TcpGetTxDataWaiting | ( | int | fd | ) |
#include <tcp.h>
Get the number of bytes queued for transmission.
Returns the number of bytes currently in the transmit buffer waiting to be sent to the remote host. This includes both data that has not yet been transmitted and data that has been transmitted but not yet acknowledged.
fd | Socket file descriptor |
void TcpSendKeepAlive | ( | int | fd | ) |
#include <tcp.h>
Send a TCP keepalive probe packet.
Transmits a TCP keepalive packet to the remote host to verify the connection is still active. The keepalive packet is an empty segment with a sequence number one less than the last sent packet. If the remote host is still connected, it will respond with a TCP ACK packet, which will update the socket's lastRxTime.
This function is used with TcpGetLastRxTime() to implement TCP keepalive functionality and detect stale or dead connections.
fd | Socket file descriptor |
Notes:
Expand for Example Usage
BOOL WaitForSocketFlush | ( | int | fd, |
uint32_t | ticks ) |
#include <tcp.h>
Wait for all transmitted data to be acknowledged.
Blocks until all data sent on the socket has been acknowledged by the remote host or until the specified timeout expires. A socket is considered "flushed" when all transmitted data has been acknowledged.
fd | Socket file descriptor |
ticks | Maximum wait time in system ticks |
TRUE | All sent data has been acknowledged |
FALSE | Timeout occurred before all data was acknowledged |