BK Controller LwIP Development Guide

[中文]

Preface

Overview

This document introduces lwIP (A Lightweight TCP/IP stack) related content, including lwIP introduction, application development, network security, and common issues. This document is mainly used for adapting lwIP and also for implementing additional features such as DNS client, DHCP server, etc.

Product Version

The product versions corresponding to this document are as follows:

Product Name

Product Version

BK7239N

V1.0

Target Audience

This document is mainly applicable to the following audiences:

  • Test Engineers

  • Software Development Engineers

Symbol Conventions

The following symbols may appear in this document, and their meanings are as follows:

Symbol

Description

High Risk

Indicates a high-risk hazard that will cause death or serious injury if not avoided.

Medium Risk

Indicates a medium-risk hazard that may cause death or serious injury if not avoided.

Low Risk

Indicates a low-risk hazard that may cause minor or moderate injury if not avoided.

Caution

Used to convey device or environmental safety warning information. If not avoided, it may cause device damage, data loss, device performance degradation, or other unpredictable results. “Caution” does not involve personal injury.

Note

Supplementary explanation of key information in the text. “Note” is not a safety warning and does not involve personal, device, or environmental harm information.

Revision History

Document Version

Release Date

Revision Description

01

2025-10-17

First official version release.

1 Overview

1.1 Background Introduction

This section introduces the background, third-party references, RFC (Request For Comments) compliance, and other content of the BEKEN Controller LwIP Development Guide.

1.2 RFC (Request For Comments) Compliance

lwIP complies with the following RFC protocol standards:

  • RFC 791 (IPv4 Standard)

  • RFC 2460 (IPv6 Standard)

  • RFC 768 (UDP) User Datagram Protocol

  • RFC 793 (TCP) Transmission Control Protocol

  • RFC 792 (ICMP) Internet Control Message Protocol

  • RFC 826 (ARP) Address Resolution Protocol

  • RFC 1035 (DNS) DOMAIN NAMES - IMPLEMENTATION AND SPECIFICATION

  • RFC 2030 (SNTP) Simple Network Timer Protocol (SNTP) Version 4 for IPv4, IPv6 and OSI

  • RFC 2131 (DHCP) Dynamic Host Configuration Protocol

  • RFC 768 (UDP) User Datagram Protocol

  • RFC 2018 (SACK) TCP Selective Acknowledgment Options

  • RFC 7323 (Window Scaling)

  • RFC 6675 (SACK for TCP) RFC 3927 (Autoip) Dynamic Configuration of IPv4

  • Link-Local Addresses

  • RFC 2236 (IGMP) Internet Group Management Protocol, Version 2

  • RFC4861 (ND for IPv6) Neighbor Discovery for IP version 6 (IPv6)

  • RFC4443 Internet Control Message Protocol (ICMPv6) for the Internet

  • Protocol Version 6 (IPv6) Specification

  • RFC4862 IPv6 Stateless Address Autoconfiguration

  • RFC2710 Multicast Listener Discovery (MLD) for IPv6

2 Features

2.1 Supported Features

BEKEN Controller lwIP uses lwIP-2.1.2 version. Unless otherwise specified, this version is used by default. BEKEN Controller lwIP supports the following features:

  • Internet Protocol version 4 (IPv4: Internet Protocol version 4)

  • Internet Protocol version 6 (IPv6: Internet Protocol version 6)

  • Internet Control Message Protocol (ICMP: Internet Control Message Protocol)

  • User Datagram Protocol (UDP: User Datagram Protocol)

  • Transmission Control Protocol (TCP: Transmission Control Protocol)

  • Domain Name System (DNS: Domain Name System) client

  • Dynamic Host Configuration Protocol (DHCP) client and server

  • Ethernet Address Resolution Protocol (ARP: Address Resolution Protocol)

  • Internet Group Management Protocol (IGMP: Internet Group Management Protocol)

  • Neighbor Discovery Protocol (ND: Neighbor Discovery)

  • Multicast Listener Discovery Protocol (MLD: Multicast Listener Discovery)

3 Development Guide

3.1 Prerequisites

lwIP development requires the following conditions:

  • Before using lwIP, update driver code based on lwIP-related configurations.

3.2 Dependencies

lwIP dependencies are as follows:

  • Depends on RTOS system calls.

  • Physical layer data transmission and reception need to be completed through the Wi-Fi driver module.

3.3 Using lwIP

lwIP provides a BSD TCP/IP socket interface through which applications can connect. The advantages of lwIP are:

  • Lightweight: lwIP has a small code size, suitable for embedded systems with limited resources.

  • Easy to port: lwIP has a clear code structure and is easy to port to different hardware platforms.

  • Easy to use: lwIP provides rich API interfaces that are easy to use.

  • Easy to maintain: lwIP has a clear code structure and is easy to maintain.

  • Easy to debug: lwIP has a clear code structure and is easy to debug.

3.4 Porting Methods

3.4.1 lwIP Initialization

lwIP supports two operating modes:

  • NO_SYS=1: No operating system mode, directly call lwip_init()

  • NO_SYS=0: Operating system mode, use tcpip_init() to create TCP/IP thread

The correct lwIP initialization method is as follows:

  • System initialization: sys_init() (if there is an operating system)

  • Memory management: mem_init(), memp_init(), pbuf_init()

  • Network interface: netif_init()

  • Protocol stack: ip_init(), arp_init(), tcp_init(), udp_init()

  • Application protocols: dns_init(), dhcp_init()

  • Timers: sys_timeouts_init()

3.4.2 Adding netif Interface and Driver Functions

After initialization, the application must add at least one Netif interface for communication.

The application needs to implement related callback functions according to the driver type. Related link layer types, MAC addresses, and send callback functions must be registered before use. If support for promiscuous mode of raw socket interface is required, a callback function implementing this function must also be registered in the driver.

Wi-Fi network interface example code is as follows:

int net_wlan_add_netif(uint8_t *mac)
{
  struct iface *wlan_if = NULL;
  netif_if_t netif_if;
  void *vif = NULL;
  int vifid = 0;
  err_t err;
  /* Get network interface type based on MAC address */
  vifid = wifi_netif_mac_to_vifid(mac);
  vif = wifi_netif_mac_to_vif(mac);
  netif_if = wifi_netif_vif_to_netif_type(vif);
  if (netif_if == NETIF_IF_AP) {
    wlan_if = &g_uap;
  } else if (netif_if == NETIF_IF_STA) {
    wlan_if = &g_mlan;
  } else {
    LWIP_LOGE("unknown netif(%d)\n", netif_if);
    return ERR_ARG;
  }
  /* Set IP address */
  ip_addr_set_ip4_u32(&wlan_if->ipaddr, INADDR_ANY);
  /* Add network interface to lwIP protocol stack */
  err = netifapi_netif_add(&wlan_if->netif,
    ip_2_ip4(&wlan_if->ipaddr),
    ip_2_ip4(&wlan_if->ipaddr),
    ip_2_ip4(&wlan_if->ipaddr),
    vif,
    wlanif_init, /* Network interface initialization callback function */
    tcpip_input); /* Input callback function */
  LWIP_LOGV("add vif%d\n", vifid);
  return ERR_OK;
}

3.5 Wi-Fi Buffer Memory and lwIP Buffer Memory

  • Wi-Fi memory block usage: Mainly for hardware receive buffers and software transmit descriptors. Hardware receive buffers are designed on the chip hardware side with default configuration size, which cannot be changed on the software side. The memory used by software transmit descriptors and SKB memory blocks are all applied from SRAM in a dynamic manner.

  • LwIP memory block usage: lwIP memory is configurable on the software side, and a certain size of MEM is taken from SRAM HEAP in a dynamic manner through macro definitions for lwIP use.

3.5.1 lwIP Memory Usage

wifi_data_flow

Controller Wi-Fi Data Path

Controller Wi-Fi data flow path is roughly divided into three layers: application layer, Wi-Fi layer, and hardware layer. The Wi-Fi layer includes lwIP layer, MAC layer, and related interface layers.

  • RX direction: During data reception, the hardware transmits received data packets to Wi-Fi receive data buffers and lwIP receive data buffers for related protocol processing, and finally uploads to the application layer. Wi-Fi receive data buffers and lwIP receive data buffers share the same buffer by default. The sizes of Wi-Fi receive data buffers and lwIP receive data buffers are all applied from SRAM HEAP. The size of lwIP receive data buffers (LWIP_MEM_SIZE) can be configured according to requirements in different scenarios.

  • TX direction: During data transmission, the application first copies the message to be sent to lwIP’s MEM (dynamically allocated memory) through the lwIP data interface for TCP/IP encapsulation, then sends the message to the Wi-Fi layer’s transmit data buffer for MAC encapsulation processing, and finally waits for transmission. To save SRAM HEAP space, Controller uses PSRAM space for data transmission copying in upper-layer applications, which alleviates SRAM memory pressure and does not reduce available memory for applications.

3.5.2 Optimize Throughput

Controller Wi-Fi performance is affected by many parameters, and there are correlations and mutual constraints between configuration parameters. If configuration parameters are reasonable and optimal, it can not only improve performance but also increase available memory for applications and improve stability.

In this section, we will briefly introduce the working mode of Wi-Fi/lwIP protocol stack and explain the role of each parameter. We will recommend corresponding parameter configurations. You can choose the most suitable configuration according to your usage scenario. Appropriately adjusting the MEM size or quantity in the above layers can improve Wi-Fi performance. Below we will introduce the parameters you need to configure.

3.5.3 lwIP Macros

lwIP provides rich macro definitions. This section mainly introduces some commonly used macro definitions. lwIP 2.1.2 has many macro configurations. Due to space limitations, not all are introduced. If needed, please refer to the official lwIP documentation.

Note
  • The default values of lwIP macros are defined in both opt.h and lwipopts.h header files.

  • Macro definitions in the lwipopts.h header file will override macro definitions in the opt.h header file, so users can modify macro definitions in the lwipopts.h header file to meet their needs.

Table 3-4 lwIP Macro List

Macro

Description

LWIP_AUTOIP

This macro is used to enable or disable the AUTOIP module.

MEM_SIZE

lwIP maintainable heap memory (including mem_malloc and mem_free) management module, used for dynamic memory allocation. This macro is used to define the size of the heap memory management module in lwIP.

MEM_LIBC_MALLOC

If this macro is enabled, the system will call malloc() and free() for all dynamic memory allocation, and the heap memory management module code in lwIP will be disabled.

MEMP_MEM_MALLOC

lwIP provides a pool memory (including memp_malloc and memp_free) management module for frequently used structures.

MEM_ALIGNMENT

The value of this macro needs to be set based on the architecture. For example, if it is a 32-bit architecture, the value of this macro needs to be set to 4.

MEMP_NUM_TCP_PCB

This macro is used to set the number of TCP connections required at the same time.

MEMP_NUM_UDP_PCB

This macro is used to set the number of UDP connections required at the same time. When setting the value of this macro, users must consider lwIP internal modules such as DNS module and DHCP module. The DHCP module will create UDP connections for its own communication.

MEMP_NUM_RAW_PCB

This macro is used to set the number of RAW connections required at the same time.

MEMP_NUM_NETCONN

This macro is used to set the total number of TCP, UDP, and RAW connections. The value of this macro must be the sum of the values of MEMP_NUM_TCP_PCB, MEMP_NUM_UDP_PCB, and MEMP_NUM_RAW_PCB macros.

MEMP_NUM_TCP_PCB_LISTEN

This macro is used to set the number of TCP connections required for listening at the same time.

MEMP_NUM_REASSDATA

This macro is used to set the number of IP packets (complete packets, not fragmented packets) queued for reassembly at the same time.

MEMP_NUM_FRAG_PBUF

This macro is used to set the number of IP packets (fragmented packets, not complete packets) sent at the same time.

ARP_TABLE_SIZE

This macro is used to set the size of the ARP cache table.

ARP_QUEUEING

Enable means there will be multiple outgoing packets queued during ARP resolution. Disable means each destination address retains the most recently sent packet from the upper layer.

MEMP_NUM_ARP_QUEUE

This macro is used to set the number of outgoing packets (pbuf) queued at the same time. These outgoing packets are waiting for ARP responses to resolve destination addresses. This macro only applies when ARP_QUEUEING is enabled.

IP_REASSEMBLY

This macro supports reassembly of IP fragmented packets.

IP_FRAG

Enable means IP fragmentation is enabled. Disable means IP fragmentation is disabled.

IP_REASS_MAX_PBUFS

This macro is used to set the maximum number of fragments allowed for any IP incoming packet.

IP_DEFAULT_TTL

Default value of transport layer data packet time to live.

LWIP_ICMP

This macro is used to enable the ICMP module.

ICMP_TTL

This macro is used to set the TTL value of ICMP messages.

LWIP_RAW

This macro supports enabling raw socket support in lwIP.

RAW_TTL

This macro is used to set the TTL value of raw socket messages.

LWIP_UDP

This macro supports enabling UDP connection support in lwIP.

UDP_TTL

This macro is used to set the TTL value of UDP socket messages.

LWIP_TCP

This macro supports enabling TCP connection support in lwIP.

TCP_TTL

This macro is used to set the TTL value of TCP socket messages.

TCP_WND

This macro is used to set the TCP window size.

TCP_MAXRTX

This macro is used to set the maximum number of retransmissions for TCP data packets.

TCP_SYNMAXRTX

This macro is used to set the maximum number of retransmissions for TCP SYN data packets.

TCP_QUEUE_OOSEQ

This macro supports caching received out-of-order data packets. If the user device has low memory, set the value of this macro to 0.

TCP_MSS

This macro is used to set the maximum segment size of TCP connections.

TCP_SND_BUF

This macro is used to set the TCP transmit data buffer size.

TCP_SND_QUEUELEN

This macro is used to set the TCP transmit queue length.

TCP_OOSEQ_MAX_BYTES

This macro is used to set the maximum number of bytes queued on ooseq for each pcb. The default value is 0 (unlimited). Only applicable when TCP_QUEUE_OOSEQ=0.

TCP_OOSEQ_MAX_PBUFS

This macro is used to set the maximum number of pbufs queued on ooseq for each pcb. The default value is 0 (unlimited). Only applicable when TCP_QUEUE_OOSEQ=0.

TCP_LISTEN_BACKLOG

This macro supports enabling backlog support when TCP is listening.

LWIP_DHCP

This macro is used to enable the DHCP client module.

LWIP_IGMP

This macro is used to enable the IGMP module.

LWIP_DNS

This macro is used to enable the DNS client module.

DNS_TABLE_SIZE

This macro is used to set the size of the DNS cache table.

DNS_MAX_NAME_LENGTH

This macro is used to set the maximum length supported by domain names. According to DNS RFC, the domain name length is set to 255. It is not recommended to modify.

DNS_MAX_SERVERS

This macro is used to set the number of DNS servers.

PBUF_LINK_HLEN

This macro is used to set the number of bytes that must be allocated to the link-level header, which should include the actual length and ETH_PAD_SIZE.

LWIP_NETIF_API

This macro is used to enable the thread-safe netif interface module (netiapi_*).

TCPIP_THREAD_NAME

This macro is used to set the name of the TCP IP thread.

DEFAULT_RAW_RECVMBOX_SIZE

Each RAW connection maintains an incoming packet queue for incoming packet caching until the application layer issues a receive notification. This macro is used to set the size of the receive message box queue.

DEFAULT_UDP_RECVMBOX_SIZE

Each UDP connection maintains an incoming packet queue for incoming packet caching until the application layer issues a receive notification. This macro is used to set the size of the receive message box queue.

DEFAULT_TCP_RECVMBOX_SIZE

Each TCP connection maintains an incoming packet queue for incoming packet caching until the application layer issues a receive notification. This macro is used to set the size of the receive message box queue.

DEFAULT_ACCEPTMBOX_SIZE

This macro is used to set the size of the message box queue to maintain incoming TCP connections.

TCPIP_MBOX_SIZE

This macro is used to set the message box queue of the TCP IP thread. This queue can maintain all operation requests issued by application threads and driver threads.

LWIP_TCPIP_TIMEOUT

This macro supports enabling the feature of running any custom timer handler function on the lwIP tcpip thread.

LWIP_COMPAT_SOCKETS

This macro can create a Linux BSD macro for all socket interfaces.

LWIP_STATS

This macro is used to statistics all online connections.

3.6 Example Code

This section lists some lwIP example code and briefly explains the uses of lwIP. These examples include pseudo-code to illustrate the interface docking and changes that need to be completed on the driver (Ethernet or Wi‑Fi) module.

Caution
  • This example code is for learning and evaluation only. Customers need to modify it according to actual conditions when using it in practice.

3.6.1 Application Example Code

3.6.1.1 UDP Example Code
#include "udp_client_demo.h"
#include <common/bk_include.h>
#include <os/os.h>
#include "lwip/sockets.h"
#include "Error.h"
#include "lwip/sockets.h"
#include "lwip/ip_addr.h"
#include "lwip/inet.h"
#include "string.h"
#include "Wlan_ui_pub.h"
#include "stdio.h"
#include "stdlib.h"
#include <components/netif.h>
beken_timer_t *udp_client_connect_timer = NULL;
int check_connect_wifi(void)
{
    netif_ip4_config_t ipStatus;
    bk_err_t ret = kNoErr;
    os_memset(&ipStatus, 0x0, sizeof(netif_ip4_config_t));
    ret = bk_netif_get_ip4_config(NETIF_IF_STA, &ipStatus);
    if(strcmp(ipStatus.ip, "0.0.0.0") != 0)
    {
        BK_LOGD(NULL, "ip:%s \r\n", ipStatus.ip);
        return 0;
    }
    return 1;
}
void udp_client_demo_thread( beken_thread_arg_t arg )
{
    bk_err_t err = kNoErr;
    struct sockaddr_in server_addr;
    socklen_t sockaddr_t_size = sizeof(server_addr);
    int SkFd = -1;
    unsigned int count = 0;
    char *buf = NULL;
    int len = 0;
    fd_set readfds;
    buf = (char *) os_malloc( 1024 );
    if(buf == NULL)
    {
        BK_LOGD(NULL, "buf == NULL\r\n");
        goto exit;
    }
    SkFd = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP );//Make UDP socket
    if(SkFd == -1)
    {
        BK_LOGD(NULL, "SkFd == -1\r\n");
        goto exit;
    }
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = IPADDR_BROADCAST;
    //server_addr.sin_addr.s_addr = inet_addr("192.168.5.103");
    server_addr.sin_port = htons(UDP_Client_Port);
    BK_LOGD(NULL, "UDP Client Run\r\n");
    while ( 1 )
    {
        sprintf(buf, "UDP Client Count:%d\r\n", count);
        count++;
        len = strlen(buf);
        len = sendto( SkFd, buf, len, 0 , (struct sockaddr *) &server_addr, sizeof(server_addr));
        rtos_delay_milliseconds( 500 );
    }
exit:
    if ( err != kNoErr )
        BK_LOGD(NULL, "udp client thread exit with err: %d", err );
    if(SkFd)
        close( SkFd );
    if(buf)
        os_free(buf);
    rtos_start_timer(udp_client_connect_timer);
    rtos_delete_thread( NULL );
}
void udp_client_check_net_timer_alarm( void *arg )
{
    bk_err_t err = kNoErr;
    (void)arg;
    if(!check_connect_wifi())
    {
        rtos_stop_timer( udp_client_connect_timer );
        err = rtos_create_thread( NULL, BEKEN_APPLICATION_PRIORITY,
                                  "udp_client",
                                  (beken_thread_function_t)udp_client_demo_thread,
                                  0x800,
                                  (beken_thread_arg_t)0 );
        if(err != kNoErr)
        {
            rtos_start_timer(udp_client_connect_timer);
        }
    }
}
int create_udp_client_check_net_timer(void)
{
    bk_err_t err;
    if(udp_client_connect_timer == NULL)
    {
        udp_client_connect_timer = (beken_timer_t *) os_malloc( sizeof(beken_timer_t) );
    }
    if(udp_client_connect_timer == NULL)
    {
        BK_LOGD(NULL, "tcp_connect_timer error!\r\n");
        return kGeneralErr;
    }
    err = rtos_init_timer(udp_client_connect_timer, 500, udp_client_check_net_timer_alarm, 0);
    if(kNoErr != err)
    {
        if(udp_client_connect_timer)
        {
            os_free(udp_client_connect_timer);
            udp_client_connect_timer = NULL;
        }
        BK_LOGD(NULL, "tcp_connect_timer error!\r\n");
    }
    return err;
}
void udp_client_connect_timer_destroy( void )
{
    rtos_deinit_timer( udp_client_connect_timer );
    if(udp_client_connect_timer)
    {
        os_free(udp_client_connect_timer);
        udp_client_connect_timer = NULL;
    }
}
int demo_start( void )
{
    bk_err_t err;
    err = create_udp_client_check_net_timer();
    if(kNoErr != err)
    {
        return err;
    }
    err = rtos_start_timer(udp_client_connect_timer);
    if(kNoErr != err)
    {
        udp_client_connect_timer_destroy();
        BK_LOGD(NULL, "timer start failed!\r\n");
        return err;
    }
    return kNoErr;
}
3.6.1.2 TCP Client Example Code
#include "tcp_client_demo.h"
#include <os/os.h>
#include "lwip/sockets.h"
#include "Error.h"
#include "lwip/sockets.h"
#include "lwip/ip_addr.h"
#include "lwip/inet.h"
#include "Common.h"
struct ip_port_msg
{
    ip4_addr_t IP;
    in_port_t  sin_port;
};
void tcp_connect_server_thread( beken_thread_arg_t arg )
{
    int SkFd = -1;
    int len = 0;
    char *buf = NULL;
    bk_err_t err = kNoErr;
    struct ip_port_msg *i_pMsg;
    struct sockaddr_in server_addr;
    socklen_t sockaddr_t_size = sizeof(server_addr);
    i_pMsg = (struct ip_port_msg *)arg;
    if(i_pMsg == NULL)
    {
        BK_LOGD(NULL, "arg err!\r\n" );
        goto exit;
    }
    SkFd = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = i_pMsg->IP.addr;    //0x0728a8c0 /*192.168.40.7*/
    server_addr.sin_port = htons(i_pMsg->sin_port);   //htons( 12345 );
    if(i_pMsg)
        os_free(i_pMsg);
    err = connect(SkFd, (struct sockaddr *) &server_addr, sizeof(server_addr));
    if(err < 0)
    {
        BK_LOGD(NULL, "connect err: %d\r\n", err );
        goto exit;
    }
    buf = (char *) os_malloc( 1024 );
    if(buf == NULL)
    {
        BK_LOGD(NULL, "buf == NULL\r\n");
        goto exit;
    }
    while ( 1 )
    {
        len = recv(SkFd, buf, 1024, 0 );
        if ( len <= 0 )
        {
            BK_LOGD(NULL, "TCP Client is disconnected, fd: %d\r\n", SkFd );
            goto exit;
        }
        len = send( SkFd, buf, len, 0 );
    }
exit:
    if ( err != kNoErr )
        BK_LOGD(NULL, "tcp_connect_server_thread exit with err: %d\r\n", err );
    if ( buf != NULL )
        os_free( buf );
    close( SkFd );
    rtos_delete_thread( NULL );
}
void tcp_make_connect_server_command(char *pcWriteBuffer, int xWriteBufferLen, int argc, char **argv)
{
    bk_err_t err = kNoErr;
    struct ip_port_msg *i_pMsg = NULL;
    int i;
    int port;
    i_pMsg = (struct ip_port_msg *) os_malloc( sizeof(struct ip_port_msg) );
    if(i_pMsg == NULL)
    {
        BK_LOGD(NULL, "i_pMsg Failed\r\n");
        return;
    }
    if(!inet_aton(argv[1], &i_pMsg->IP.addr))
    {
        BK_LOGD(NULL, "inet_aton Failed\r\n");
        goto exit;
    }
    port = num_string2uint16num(argv[2]);
    if(port < 0)
    {
        BK_LOGD(NULL, "port err:%d\r\n", port);
    }
    i_pMsg->sin_port = port;
    err = rtos_create_thread( NULL,
                              BEKEN_APPLICATION_PRIORITY,
                              "connt_Server",
                              tcp_connect_server_thread,
                              0x600,
                              i_pMsg );
    if(kNoErr != err)
    {
        BK_LOGD(NULL, "rtos_create_thread Failed(%d)\r\n", err);
        goto exit;
    }
    return;
exit:
    if(i_pMsg)
        os_free(i_pMsg);
}

3.7 lwIP Troubleshooting Guide

3.7.2 lwIP Debug Commands

BEKEN Controller lwIP currently supports lwip_mem and lwip_stats to locate TCP/IP related issues.

lwip_mem - View memory usage related to lwIP. This command returns the following:

$lwip_mem

Name             total used addr       size  err      comment
---------------------------------------------------------------
RAW_PCB          4     0    0x2804ebbf 28    0     # Raw protocol control block, for direct access to IP layer
UDP_PCB          10    1    0x2804fc07 40    0     # UDP protocol control block, manages UDP connections
TCP_PCB          8     0    0x2804f0a1 164   0     # TCP protocol control block, manages TCP connection state
TCP_PCB_LISTEN   4     0    0x2804f01e 32    0     # TCP listen control block, for listening TCP connections
TCP_SEG          80    0    0x2804f5c4 20    0     # TCP segment structure, manages TCP data segments
REASSDATA        5     0    0x2804ec32 32    0     # IP fragment reassembly data structure
FRAG_PBUF        15    0    0x28049c2a 24    0     # Fragment buffer, stores IP fragment data
NETBUF           32    0    0x28049e18 16    0     # Network buffer, for packet transmission
NETCONN          20    0    0x2804a01b 52    0     # Network connection abstraction, application interface
TCPIP_MSG_API    8     0    0x2804ed98 16    0     # TCP/IP API message structure
TCPIP_MSG_INPKT  32    0    0x2804ee1b 16    0     # Input packet message structure
ARP_QUEUE        4     0    0x28049c07 8     0     # ARP request queue
IGMP_GROUP       8     1    0x28049d95 16    0     # IGMP group management structure
SYS_TIMEOUT      12    6    0x2804ecd5 16    0     # System timeout structure
NETDB            4     0    0x2804a42e 308   0     # Network database structure
PBUF_REF/ROM     10    0    0x2804eb1c 16    0     # Reference/read-only data buffer
PBUF_POOL        10    0    0x2804a901 1692  0     # Data buffer pool
===== MEMP_PBUF_POOL ======
avail 10, used 0, max 0, err 0
========== MEM ============
avail 51200, used 60, max 1124, err 0
tx avail 42666, rx avail 38400, tx used 60, rx used 0, tx max 544, rx max 1064, tx err 0, rx err 0

lwip_stats - View lwIP transmission and reception statistics. This command returns the following:

$lwip_stats

ETHARP
xmit:     2
recv:     5
fw:       0
drop:     0

chkerr:   0
lenerr:   0
memerr:   0
rterr:    0
proterr:  0
opterr:   0
err:      0
cachehit: 5
IP
xmit:     10
recv:     16
fw:       0
drop:     5
chkerr:   0
lenerr:   0
memerr:   0
rterr:    0
proterr:  0
opterr:   0
err:      0
cachehit: 0
UDP
xmit:     4
recv:     5
fw:       0
drop:     0
chkerr:   0
lenerr:   0
memerr:   0
rterr:    0
proterr:  0
opterr:   0
err:      0
cachehit: 4
TCP
xmit:     0
recv:     0
fw:       0
drop:     0
chkerr:   0
lenerr:   0
memerr:   0
rterr:    0
proterr:  0
opterr:   0
err:      0
cachehit: 0
Note
  • Using lwip_mem and lwip_stats commands requires ensuring that the cli_lwip.c module is included in the compilation.

4 Network Security

4.1 Network Security Statement

To avoid sensitive information leakage, users must pay attention to the following security considerations:

Debug logs: By configuring the macro LWIP_DEBUG in the lwipopts.h header file, you can enable or disable DebugFlag. This macro is disabled by default.

Table 4-1 Debug Disable Options

Option Code

Recommended Value

Impact

LWIP_DEBUG

LWIP_DBG_OFF

When LWIP_DBG_ON is enabled, if this value is set to 1, some user sensitive information may be leaked.

5 Common Issues

Question 1: Does lwIP support the route command?

Answer: lwIP does not support the route command.

Question 2: What is lwIP’s routing mechanism?

Answer: lwIP does not support route selection, but if the IP_FORWARD flag is enabled, lwIP supports forwarding packets through routing.

Question 3: Can lwIP run normally without adding netif?

Answer: No. Netif must be added and callbacks must be executed.

Question 4: Does lwIP support IPv4 multicast?

Answer: Yes. This function can be enabled by setting LWIP_IGMP to 1 and using setsockopt() to set IP_ADD_MEMBERSHIP and IP_DROP_MEMBERSHIP, etc.

Question 5: What is the impact of IP address changes on TCP connections?

Answer: All existing TCP connections will be dropped, and any TCP connection operations will return ECONNABORTED. All bound addresses are modified to the new IP address. If there is a listening socket, it will accept connections on the new IP address.

Question 6: What is the impact of IP address changes on UDP connections?

Answer: The IP addresses of all sockets are modified to the new IP address. Communication continues on the new IP address.

Question 7: How to adjust lwIP receive window related configuration?

Answer: You can refer to the 3.5.2 Optimize Throughput section about adjusting lwIP receive window related configuration.

6 Terms

Abbreviation

Term

Description

ARP

Address Resolution Protocol

Address Resolution Protocol is a network protocol that converts IP addresses to physical addresses.

DHCP

Dynamic Host Configuration Protocol

Dynamic Host Configuration Protocol is a standardized networking protocol used on IP networks to dynamically assign network configuration parameters such as IP addresses to interfaces and services.

lwIP

Lightweight TCP/IP Protocol Stack

lwIP is a lightweight open-source TCP/IP protocol stack widely used in embedded systems.

RTOS

Real-Time Operating System

Real-Time Operating System is a real-time operating system used to provide real-time capabilities for embedded systems.

ICMP

Internet Control Message Protocol

Internet Control Message Protocol is a protocol used by network devices such as routers to send error messages to indicate that the requested service is unavailable or the host cannot be reached.

IP

Internet Protocol

A protocol in the TCP/IP protocol suite that controls the encapsulation of segmented data messages into packets, the routing of packets from the sending station to the destination network and station, and the combination into original data information at the target station. The IP protocol runs at the internet layer of the TCP/IP model, corresponding to the network layer of the ISO/OSI model.

IoT

Internet of Things

A network that is an information carrier such as the Internet and traditional telecommunications networks, enabling all ordinary objects that can perform independent functions to achieve interconnection.

TCP

Transmission Control Protocol

A protocol in TCP/IP used to decompose data information into packets for transmission through the IP protocol, and to verify and reassemble information packets received through the IP protocol into complete information. TCP is a connection-oriented reliable protocol that ensures error-free transmission of information, corresponding to the transport layer in the ISO/OSI reference model.

UDP

User Datagram Protocol

A TCP/IP standard protocol that allows applications on one device to send datagrams to applications on another device. UDP uses IP to transmit datagrams, providing unreliable connectionless message transmission services for applications. That is, UDP messages may be lost, duplicated, delayed, or out of order. The destination device does not actively confirm whether the correct packet was received.

Document Version 01 (2025-10-17) Copyright © Beken Corporation