Networking API

This is the full set of networking public APIs. Their exposure depends on relevant Kconfig options. For instance IPv6 related APIs will not be present if CONFIG_NET_IPV6 has not been selected.

IPv4/IPv6 primitives and helpers

enum ip_4_6::net_ip_protocol

Protocol numbers from IANA

Values:

IPPROTO_ICMP = 1
IPPROTO_TCP = 6
IPPROTO_UDP = 17
IPPROTO_ICMPV6 = 58
enum ip_4_6::net_sock_type

Socket type

Values:

SOCK_DGRAM = 1
SOCK_STREAM
enum ip_4_6::net_addr_type

How the network address is assigned to network interface

Values:

NET_ADDR_ANY = 0
NET_ADDR_AUTOCONF
NET_ADDR_DHCP
NET_ADDR_MANUAL
enum ip_4_6::net_addr_state

What is the current state of the network address

Values:

NET_ADDR_ANY_STATE = -1
NET_ADDR_TENTATIVE = 0
NET_ADDR_PREFERRED
NET_ADDR_DEPRECATED
typedef unsigned short int sa_family_t
typedef size_t socklen_t
struct net_tcp_hdr __packed
static char *net_addr_type2str(enum net_addr_type type)
static bool net_is_ipv6_addr_loopback(struct in6_addr *addr)

Check if the IPv6 address is a loopback address (::1).

Return
True if address is a loopback address, False otherwise.
Parameters
  • addr: IPv6 address

static bool net_is_ipv6_addr_mcast(const struct in6_addr *addr)

Check if the IPv6 address is a multicast address.

Return
True if address is multicast address, False otherwise.
Parameters
  • addr: IPv6 address

struct net_if_addr *net_if_ipv6_addr_lookup(const struct in6_addr *addr, struct net_if **iface)
static bool net_is_my_ipv6_addr(struct in6_addr *addr)

Check if IPv6 address is found in one of the network interfaces.

Return
True if address was found, False otherwise.
Parameters
  • addr: IPv6 address

struct net_if_mcast_addr *net_if_ipv6_maddr_lookup(const struct in6_addr *addr, struct net_if **iface)
static bool net_is_my_ipv6_maddr(struct in6_addr *maddr)

Check if IPv6 multicast address is found in one of the network interfaces.

Return
True if address was found, False otherwise.
Parameters
  • maddr: Multicast IPv6 address

static bool net_is_ipv6_prefix(const uint8_t *addr1, const uint8_t *addr2, uint8_t length)

Check if two IPv6 addresses are same when compared after prefix mask.

Return
True if IPv6 prefixes are the same, False otherwise.
Parameters
  • addr1: First IPv6 address.
  • addr2: Second IPv6 address.
  • length: Prefix length (max length is 128).

static bool net_is_ipv4_addr_loopback(struct in_addr *addr)

Check if the IPv4 address is a loopback address (127.0.0.0/8).

Return
True if address is a loopback address, False otherwise.
Parameters
  • addr: IPv4 address

static bool net_is_ipv4_addr_unspecified(const struct in_addr *addr)

Check if the IPv4 address is unspecified (all bits zero)

Return
True if the address is unspecified, false otherwise.
Parameters
  • addr: IPv4 address.

static bool net_is_ipv4_addr_mcast(const struct in_addr *addr)

Check if the IPv4 address is a multicast address.

Return
True if address is multicast address, False otherwise.
Parameters
  • addr: IPv4 address

struct net_if_addr *net_if_ipv4_addr_lookup(const struct in_addr *addr, struct net_if **iface)
static bool net_is_my_ipv4_addr(const struct in_addr *addr)

Check if the IPv4 address is assigned to any network interface in the system.

Return
True if IPv4 address is found in one of the network interfaces, False otherwise.
Parameters
  • addr: A valid pointer on an IPv4 address

static bool net_ipv4_addr_cmp(const struct in_addr *addr1, const struct in_addr *addr2)

Compare two IPv4 addresses.

Return
True if the addresses are the same, false otherwise.
Parameters
  • addr1: Pointer to IPv4 address.
  • addr2: Pointer to IPv4 address.

static bool net_ipv6_addr_cmp(const struct in6_addr *addr1, const struct in6_addr *addr2)

Compare two IPv6 addresses.

Return
True if the addresses are the same, false otherwise.
Parameters
  • addr1: Pointer to IPv6 address.
  • addr2: Pointer to IPv6 address.

static bool net_is_ipv6_ll_addr(const struct in6_addr *addr)

Check if the given IPv6 address is a link local address.

Return
True if it is, false otherwise.
Parameters
  • addr: A valid pointer on an IPv6 address

const struct in6_addr *net_ipv6_unspecified_address(void)

Return pointer to any (all bits zeros) IPv6 address.

Return
Any IPv6 address.

const struct in_addr *net_ipv4_unspecified_address(void)

Return pointer to any (all bits zeros) IPv4 address.

Return
Any IPv4 address.

const struct in_addr *net_ipv4_broadcast_address(void)

Return pointer to broadcast (all bits ones) IPv4 address.

Return
Broadcast IPv4 address.

bool net_if_ipv4_addr_mask_cmp(struct net_if *iface, struct in_addr *addr)
static bool net_ipv4_addr_mask_cmp(struct net_if *iface, struct in_addr *addr)

Check if the given address belongs to same subnet that has been configured for the interface.

Return
True if address is in same subnet, false otherwise.
Parameters
  • iface: A valid pointer on an interface
  • addr: pointer on an address

static bool net_is_ipv6_addr_unspecified(const struct in6_addr *addr)

Check if the IPv6 address is unspecified (all bits zero)

Return
True if the address is unspecified, false otherwise.
Parameters
  • addr: IPv6 address.

static bool net_is_ipv6_addr_solicited_node(const struct in6_addr *addr)

Check if the IPv6 address is solicited node multicast address FF02:0:0:0:0:1:FFXX:XXXX defined in RFC 3513.

Return
True if the address is solicited node address, false otherwise.
Parameters
  • addr: IPv6 address.

static bool net_is_ipv6_addr_mcast_global(const struct in6_addr *addr)

Check if the IPv6 address is a global multicast address (FFxE::/16).

Return
True if the address is global multicast address, false otherwise.
Parameters
  • addr: IPv6 address.

static void net_ipv6_addr_create_solicited_node(struct in6_addr *src, struct in6_addr *dst)

Create solicited node IPv6 multicast address FF02:0:0:0:0:1:FFXX:XXXX defined in RFC 3513.

Parameters
  • src: IPv6 address.
  • dst: IPv6 address.

static void net_ipv6_addr_create(struct in6_addr *addr, uint16_t addr0, uint16_t addr1, uint16_t addr2, uint16_t addr3, uint16_t addr4, uint16_t addr5, uint16_t addr6, uint16_t addr7)

Construct an IPv6 address from eight 16-bit words.

Parameters
  • addr: IPv6 address
  • addr0: 16-bit word which is part of the address
  • addr1: 16-bit word which is part of the address
  • addr2: 16-bit word which is part of the address
  • addr3: 16-bit word which is part of the address
  • addr4: 16-bit word which is part of the address
  • addr5: 16-bit word which is part of the address
  • addr6: 16-bit word which is part of the address
  • addr7: 16-bit word which is part of the address

static void net_ipv6_addr_create_ll_allnodes_mcast(struct in6_addr *addr)

Create link local allnodes multicast IPv6 address.

Parameters
  • addr: IPv6 address

static void net_ipv6_addr_create_iid(struct in6_addr *addr, struct net_linkaddr *lladdr)

Create IPv6 address interface identifier.

Parameters
  • addr: IPv6 address
  • lladdr: Link local address

static bool net_ipv6_addr_based_on_ll(const struct in6_addr *addr, const struct net_linkaddr *lladdr)

Check if given address is based on link layer address.

Return
True if it is, False otherwise

static struct sockaddr_in6 *net_sin6(const struct sockaddr *addr)

Get sockaddr_in6 from sockaddr. This is a helper so that the code calling this function can be made shorter.

Return
Pointer to IPv6 socket address
Parameters
  • addr: Socket address

static struct sockaddr_in *net_sin(const struct sockaddr *addr)

Get sockaddr_in from sockaddr. This is a helper so that the code calling this function can be made shorter.

Return
Pointer to IPv4 socket address
Parameters
  • addr: Socket address

static struct sockaddr_in6_ptr *net_sin6_ptr(const struct sockaddr_ptr *addr)

Get sockaddr_in6_ptr from sockaddr_ptr. This is a helper so that the code calling this function can be made shorter.

Return
Pointer to IPv6 socket address
Parameters
  • addr: Socket address

static struct sockaddr_in_ptr *net_sin_ptr(const struct sockaddr_ptr *addr)

Get sockaddr_in_ptr from sockaddr_ptr. This is a helper so that the code calling this function can be made shorter.

Return
Pointer to IPv4 socket address
Parameters
  • addr: Socket address

int net_addr_pton(sa_family_t family, const char *src, void *dst)

Convert a string to IP address.

Note
This function doesn’t do precise error checking, do not use for untrusted strings.
Return
0 if ok, < 0 if error
Parameters
  • family: IP address family (AF_INET or AF_INET6)
  • src: IP address in a null terminated string
  • dst: Pointer to struct in_addr if family is AF_INET or pointer to struct in6_addr if family is AF_INET6

char *net_addr_ntop(sa_family_t family, const void *src, char *dst, size_t size)

Convert IP address to string form.

Return
dst pointer if ok, NULL if error
Parameters
  • family: IP address family (AF_INET or AF_INET6)
  • src: Pointer to struct in_addr if family is AF_INET or pointer to struct in6_addr if family is AF_INET6
  • dst: IP address in a non-null terminated string
  • size: Number of bytes available in the buffer

PF_UNSPEC 0 /* Unspecified. */

Protocol families

PF_INET 2 /* IP protocol family. */
PF_INET6 10 /* IP version 6. */
AF_UNSPEC PF_UNSPEC

Address families.

AF_INET PF_INET
AF_INET6 PF_INET6
ntohs(x) sys_be16_to_cpu(x)
ntohl(x) sys_be32_to_cpu(x)
htons(x) sys_cpu_to_be16(x)
htonl(x) sys_cpu_to_be32(x)
IN6ADDR_ANY_INIT { { { 0, 0, 0, 0, 0, 0, 0, 0, 0, \ 0, 0, 0, 0, 0, 0, 0 } } }
IN6ADDR_LOOPBACK_INIT { { { 0, 0, 0, 0, 0, 0, 0, \ 0, 0, 0, 0, 0, 0, 0, 0, 1 } } }
INET6_ADDRSTRLEN 46
NET_IPV6_ADDR_LEN sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx")
NET_IPV4_ADDR_LEN sizeof("xxx.xxx.xxx.xxx")
INADDR_ANY 0
INADDR_ANY_INIT { { { INADDR_ANY } } }
NET_IPV6_MTU 1280
NET_IPV6_NEXTHDR_HBHO 0

IPv6 extension headers types

NET_IPV6_NEXTHDR_DESTO 60
NET_IPV6_NEXTHDR_ROUTING 43
NET_IPV6_NEXTHDR_FRAG 44
NET_IPV6_NEXTHDR_NONE 59
NET_UDPH_LEN 8 /* Size of UDP header */
NET_TCPH_LEN 20 /* Size of TCP header */
NET_ICMPH_LEN 4 /* Size of ICMP header */
NET_IPV6H_LEN 40 /* Size of IPv6 header */
NET_ICMPV6H_LEN NET_ICMPH_LEN /* Size of ICMPv6 header */
NET_IPV6UDPH_LEN (NET_UDPH_LEN + NET_IPV6H_LEN) /* IPv6 + UDP */
NET_IPV6TCPH_LEN (NET_TCPH_LEN + NET_IPV6H_LEN) /* IPv6 + TCP */
NET_IPV6ICMPH_LEN (NET_IPV6H_LEN + NET_ICMPH_LEN) /* ICMPv6 + IPv6 */
NET_IPV6_FRAGH_LEN 8
NET_IPV4H_LEN 20 /* Size of IPv4 header */
NET_ICMPV4H_LEN NET_ICMPH_LEN /* Size of ICMPv4 header */
NET_IPV4UDPH_LEN (NET_UDPH_LEN + NET_IPV4H_LEN) /* IPv4 + UDP */
NET_IPV4TCPH_LEN (NET_TCPH_LEN + NET_IPV4H_LEN) /* IPv4 + TCP */
NET_IPV4ICMPH_LEN (NET_IPV4H_LEN + NET_ICMPH_LEN) /* ICMPv4 + IPv4 */
net_ipaddr_copy(dest, src) UNALIGNED_PUT(UNALIGNED_GET(src), dest)

Copy an IPv4 or IPv6 address.

Return
Destination address.
Parameters
  • dest: Destination IP address.
  • src: Source IP address.

__packed __attribute__((packed))
struct in6_addr
#include <net_ip.h>

IPv6 address structure

union

Public Members

struct in_addr
#include <net_ip.h>

IPv4 address

union

Public Members

struct sockaddr_in6
#include <net_ip.h>

Note that the sin_port and sin6_port are in network byte order in various sockaddr* structs.

struct net_tuple
#include <net_ip.h>

IPv6/IPv4 network connection tuple

Network interface

enum [anonymous]__anonymous78

Values:

NET_IF_UP
NET_IF_POINTOPOINT
NET_IF_NUM_FLAGS

Define callback that is called after a network packet has been sent.

Parameters
  • struct net_if *iface: A pointer on a struct net_if to which the the net_buf was sent to.
  • struct net_linkaddr *dst: Link layer address of the destination where the network packet was sent.
  • int status: Send status, 0 is ok, < 0 error.

typedef net_if_cb_t

Callback used while iterating over network interfaces.

Parameters
  • iface: Pointer to current network interface
  • user_data: A valid pointer on some user data or NULL

struct net_if_link_cb __aligned
struct net_if __aligned(32)
enum net_verdict net_if_send_data(struct net_if *iface, struct net_buf *buf)

Send a buffer through a net iface.

return verdict about the packet

Parameters
  • iface: Pointer to a network interface structure
  • buf: Pointer on a net buffer to send

static enum net_verdict net_if_recv_data(struct net_if *iface, struct net_buf *buf)

Input a buffer through a net iface.

Return
verdict about the packet
Parameters
  • iface: Pointer to a network interface structure
  • buf: Pointer on a net buffer to input

static uint16_t net_if_get_ll_reserve(struct net_if *iface, const struct in6_addr *dst_ip6)

Get link layer header size for this network interface.

Return
Return the link layer header size
Parameters
  • iface: Pointer to a network interface structure
  • dst_ip6: Pointer on the distant IPv6 or NULL if not relevant

static void *net_if_l2_data(struct net_if *iface)

Get a pointer on L2’s private data.

Return
a pointer on the iface’s l2 data
Parameters
  • iface: a valid pointer to a network interface structure

static struct device *net_if_get_device(struct net_if *iface)

Get an network interface’s device.

Return
a pointer on the device driver instance
Parameters
  • iface: Pointer to a network interface structure

static void net_if_queue_tx(struct net_if *iface, struct net_buf *buf)

Queue a packet into net if’s TX queue.

Parameters
  • iface: Pointer to a network interface structure
  • buf: Pointer on a net buffer to queue

static bool net_if_is_ip_offloaded(struct net_if *iface)

Return the IP offload status.

Return
True if IP offlining is active, false otherwise.
Parameters
  • iface: Network interface

Get an network interface’s link address.

Return
a pointer on the network link address
Parameters
  • iface: Pointer to a network interface structure

void net_if_start_rs(struct net_if *iface)

Start neighbor discovery and send router solicitation message.

Parameters
  • iface: Pointer to a network interface structure

Set a network interface’s link address.

Return
0 on success
Parameters
  • iface: Pointer to a network interface structure
  • addr: a pointer on a uint8_t buffer representing the address
  • len: length of the address buffer
  • type: network bearer type of this link address

static uint16_t net_if_get_mtu(struct net_if *iface)

Get an network interface’s MTU.

Return
the MTU
Parameters
  • iface: Pointer to a network interface structure

static void net_if_set_mtu(struct net_if *iface, uint16_t mtu)

Set an network interface’s MTU.

Parameters
  • iface: Pointer to a network interface structure
  • mtu: New MTU, note that we store only 16 bit mtu value.

static void net_if_addr_set_lf(struct net_if_addr *ifaddr, bool is_infinite)

Set the infinite status of the network interface address.

Parameters
  • ifaddr: IP address for network interface
  • is_infinite: Infinite status

Get an interface according to link layer address.

Return
Network interface or NULL if not found.
Parameters
  • ll_addr: Link layer address.

struct net_if *net_if_lookup_by_dev(struct device *dev)

Find an interface from it’s related device.

Return
a valid struct net_if pointer on success, NULL otherwise
Parameters
  • dev: A valid struct device pointer to relate with an interface

static void net_if_router_rm(struct net_if_router *router)

Remove a router from the system.

Parameters
  • router: Pointer to existing router

struct net_if *net_if_get_default(void)

Get the default network interface.

Return
Default interface or NULL if no interfaces are configured.

Register a link callback.

Parameters
  • link: Caller specified handler for the callback.
  • cb: Callback to register.

Unregister a link callback.

Parameters
  • link: Caller specified handler for the callback.

Call a link callback function.

Parameters
  • iface: Network interface.
  • lladdr: Destination link layer address
  • status: 0 is ok, < 0 error

struct net_if *net_if_get_by_index(uint8_t index)

Get interface according to index.

Return
Pointer to interface or NULL if not found.
Parameters
  • index: Interface index

uint8_t net_if_get_by_iface(struct net_if *iface)

Get interface index according to pointer.

Return
Interface index
Parameters
  • iface: Pointer to network interface

void net_if_foreach(net_if_cb_t cb, void *user_data)

Go through all the network interfaces and call callback for each interface.

Parameters
  • cb: User supplied callback function to call.
  • user_data: User specified data.

int net_if_up(struct net_if *iface)

Bring interface up.

Return
0 on success
Parameters
  • iface: Pointer to network interface

int net_if_down(struct net_if *iface)

Bring interface down.

Return
0 on success
Parameters
  • iface: Pointer to network interface

__net_if_align __aligned(32)
net_if_start_dad(iface)

Start duplicate address detection procedure.

Parameters
  • iface: Pointer to a network interface structure

net_if_ipv6_select_src_addr(...)
NET_IF_GET_NAME(dev_name, sfx) (__net_if_##dev_name##_##sfx)
NET_IF_GET(dev_name, sfx) ((struct net_if *)&NET_IF_GET_NAME(dev_name, sfx))
NET_IF_INIT(dev_name, sfx, _l2, _mtu) static struct net_if (NET_IF_GET_NAME(dev_name, sfx)) __used \ __attribute__((__section__(".net_if.data"))) = { \ .dev = &(__device_##dev_name), \ .l2 = &(NET_L2_GET_NAME(_l2)), \ .l2_data = &(NET_L2_GET_DATA(dev_name, sfx)), \ .mtu = _mtu, \ }; \ NET_STACK_INFO_ADDR(TX, \ dev_name, \ CONFIG_NET_TX_STACK_SIZE, \ CONFIG_NET_TX_STACK_SIZE, \ NET_IF_GET(dev_name, sfx)->tx_stack, \ sfx)
NET_DEVICE_INIT(dev_name, drv_name, init_fn, data, cfg_info, prio, api, l2, l2_ctx_type, mtu) DEVICE_AND_API_INIT(dev_name, drv_name, init_fn, data, \ cfg_info, POST_KERNEL, prio, api); \ NET_L2_DATA_INIT(dev_name, 0, l2_ctx_type); \ NET_IF_INIT(dev_name, 0, l2, mtu)
NET_DEVICE_INIT_INSTANCE(dev_name, drv_name, instance, init_fn, data, cfg_info, prio, api, l2, l2_ctx_type, mtu) DEVICE_AND_API_INIT(dev_name, drv_name, init_fn, data, \ cfg_info, POST_KERNEL, prio, api); \ NET_L2_DATA_INIT(dev_name, instance, l2_ctx_type); \ NET_IF_INIT(dev_name, instance, l2, mtu)

If your network device needs more than one instance of a network interface, Use this macro below and provide a different instance suffix each time (0, 1, 2, ... or a, b, c ... whatever works for you)

struct net_if_addr
#include <net_if.h>

Network Interface unicast IP addresses.

Stores the unicast IP addresses assigned to this network interface.

struct net_if_mcast_addr
#include <net_if.h>

Network Interface multicast IP addresses.

Stores the multicast IP addresses assigned to this network interface.

struct net_if_router
#include <net_if.h>

Information about routers in the system.

Stores the router information.

struct net_if
#include <net_if.h>

Network Interface structure.

Used to handle a network interface on top of a device driver instance. There can be many net_if instance against the same device.

Such interface is mainly to be used by the link layer, but is also tight to a network context: it then makes the relation with a network context and the network device.

Because of the strong relationship between a device driver and such network interface, each net_if should be instantiated by

#include <net_if.h>

Link callback handler struct.

Stores the link callback information. Caller must make sure that the variable pointed by this is valid during the lifetime of registration. Typically this means that the variable cannot be allocated from stack.

Network Management

typedef net_mgmt_request_handler_t

Signature which all Net MGMT request handler need to follow.

Parameters
  • mgmt_request: The exact request value the handler is being called through
  • iface: A valid pointer on struct net_if if the request is meant to be tight to a network interface. NULL otherwise.
  • data: A valid pointer on a data understood by the handler. NULL otherwise.
  • len: Length in byte of the memory pointed by data.

typedef net_mgmt_event_handler_t

Define the user’s callback handler function signature.

Parameters
  • struct net_mgmt_event_callback *cb: Original struct net_mgmt_event_callback owning this handler.
  • uint32_t mgmt_event: The network event being notified.
  • struct net_if *iface: A pointer on a struct net_if to which the the event belongs to, if it’s an event on an iface. NULL otherwise.

NET_MGMT_EVENT_MASK 0x80000000

NET MGMT event mask basics, normalizing parts of bit fields.

NET_MGMT_ON_IFACE_MASK 0x40000000
NET_MGMT_LAYER_MASK 0x30000000
NET_MGMT_LAYER_CODE_MASK 0x0FFF0000
NET_MGMT_COMMAND_MASK 0x0000FFFF
NET_MGMT_EVENT_BIT BIT(31)
NET_MGMT_IFACE_BIT BIT(30)
NET_MGMT_LAYER(_layer) (_layer << 28)
NET_MGMT_LAYER_CODE(_code) (_code << 16)
NET_MGMT_EVENT(mgmt_request) (mgmt_request & NET_MGMT_EVENT_MASK)
NET_MGMT_ON_IFACE(mgmt_request) (mgmt_request & NET_MGMT_ON_IFACE_MASK)
NET_MGMT_GET_LAYER(mgmt_request) ((mgmt_request & NET_MGMT_LAYER_MASK) >> 28)
NET_MGMT_GET_LAYER_CODE(mgmt_request) ((mgmt_request & NET_MGMT_LAYER_CODE_MASK) >> 16)
NET_MGMT_GET_COMMAND(mgmt_request) (mgmt_request & NET_MGMT_COMMAND_MASK)
NET_MGMT_LAYER_L1 1
NET_MGMT_LAYER_L2 2
NET_MGMT_LAYER_L3 3
net_mgmt(_mgmt_request, _iface, _data, _len) net_mgmt_##_mgmt_request(_mgmt_request, _iface, _data, _len)
NET_MGMT_DEFINE_REQUEST_HANDLER(_mgmt_request) extern int net_mgmt_##_mgmt_request(uint32_t mgmt_request, \ struct net_if *iface, \ void *data, size_t len)
NET_MGMT_REGISTER_REQUEST_HANDLER(_mgmt_request, _func) FUNC_ALIAS(_func, net_mgmt_##_mgmt_request, int)
net_mgmt_init_event_callback(...)
net_mgmt_add_event_callback(...)
net_mgmt_event_notify(...)
net_mgmt_event_init(...)
struct net_mgmt_event_callback
#include <net_mgmt.h>

Network Management event callback structure Used to register a callback into the network management event part, in order to let the owner of this struct to get network event notification based on given event mask.

Application network context

enum net_context::net_context_state

State of the context (bits 1 & 2 in the flags)

Values:

NET_CONTEXT_IDLE = 0
NET_CONTEXT_UNCONNECTED = 0
NET_CONTEXT_CONFIGURING = 1
NET_CONTEXT_CONNECTING = 1
NET_CONTEXT_READY = 2
NET_CONTEXT_CONNECTED = 2
NET_CONTEXT_LISTENING = 3
typedef net_context_recv_cb_t

Network data receive callback.

The recv callback is called after a network data is received.

Parameters
  • context: The context to use.
  • buf: Network buffer that is received. If the buf is not NULL, then the callback will own the buffer and it needs to to unref the buf as soon as it has finished working with it. On EOF, buf will be NULL.
  • status: Value is set to 0 if some data or the connection is at EOF, <0 if there was an error receiving data, in this case the buf parameter is set to NULL.
  • user_data: The user data given in net_recv() call.

typedef net_context_send_cb_t

Network data send callback.

The send callback is called after a network data is sent.

Parameters
  • context: The context to use.
  • status: Value is set to 0 if all data was sent ok, <0 if there was an error sending data. >0 amount of data that was sent when not all data was sent ok.
  • token: User specified value specified in net_send() call.
  • user_data: The user data given in net_send() call.

typedef net_tcp_accept_cb_t

Accept callback.

The accept callback is called after a successful connection is being established or if there was an error while we were waiting for a connection attempt.

Parameters
  • context: The context to use.
  • addr: The peer address.
  • addrlen: Length of the peer address.
  • status: The status code, 0 on success, < 0 otherwise
  • user_data: The user data given in net_context_accept() call.

typedef net_context_connect_cb_t

Connection callback.

The connect callback is called after a connection is being established.

Parameters
  • context: The context to use.
  • status: Status of the connection establishment. This is 0 if the connection was established successfully, <0 if there was an error.
  • user_data: The user data given in net_context_connect() call.

typedef net_context_cb_t

Callback used while iterating over network contexts.

Parameters
  • context: A valid pointer on current network context
  • user_data: A valid pointer on some user data or NULL

static bool net_context_is_used(struct net_context *context)
static enum net_context_state net_context_get_state(struct net_context *context)

Get state for this network context.

This function returns the state of the context.

Return
Network state.
Parameters
  • context: Network context.

static void net_context_set_state(struct net_context *context, enum net_context_state state)

Set state for this network context.

This function sets the state of the context.

Parameters
  • context: Network context.
  • state: New network context state.

static sa_family_t net_context_get_family(struct net_context *context)

Get address family for this network context.

This function returns the address family (IPv4 or IPv6) of the context.

Return
Network state.
Parameters
  • context: Network context.

static void net_context_set_family(struct net_context *context, sa_family_t family)

Set address family for this network context.

This function sets the address family (IPv4 or IPv6) of the context.

Parameters
  • context: Network context.
  • family: Address family (AF_INET or AF_INET6)

static enum net_sock_type net_context_get_type(struct net_context *context)

Get context type for this network context.

This function returns the context type (stream or datagram) of the context.

Return
Network context type.
Parameters
  • context: Network context.

static void net_context_set_type(struct net_context *context, enum net_sock_type type)

Set context type for this network context.

This function sets the context type (stream or datagram) of the context.

Parameters
  • context: Network context.
  • type: Context type (SOCK_STREAM or SOCK_DGRAM)

static enum net_ip_protocol net_context_get_ip_proto(struct net_context *context)

Get context IP protocol for this network context.

This function returns the context IP protocol (UDP / TCP) of the context.

Return
Network context IP protocol.
Parameters
  • context: Network context.

static void net_context_set_ip_proto(struct net_context *context, enum net_ip_protocol ip_proto)

Set context IP protocol for this network context.

This function sets the context IP protocol (UDP / TCP) of the context.

Parameters
  • context: Network context.
  • ip_proto: Context IP protocol (IPPROTO_UDP or IPPROTO_TCP)

static struct net_if *net_context_get_iface(struct net_context *context)

Get network interface for this context.

This function returns the used network interface.

Return
Context network interface if context is bind to interface, NULL otherwise.
Parameters
  • context: Network context.

static void net_context_set_iface(struct net_context *context, struct net_if *iface)

Set network interface for this context.

This function binds network interface to this context.

Parameters
  • context: Network context.
  • iface: Network interface.

int net_context_get(sa_family_t family, enum net_sock_type type, enum net_ip_protocol ip_proto, struct net_context **context)

Get network context.

Network context is used to define the connection 5-tuple (protocol, remote address, remote port, source address and source port). Random free port number will be assigned to source port when context is created. This is similar as BSD socket() function. The context will be created with a reference count of 1.

Return
0 if ok, < 0 if error
Parameters
  • family: IP address family (AF_INET or AF_INET6)
  • type: Type of the socket, SOCK_STREAM or SOCK_DGRAM
  • ip_proto: IP protocol, IPPROTO_UDP or IPPROTO_TCP
  • context: The allocated context is returned to the caller.

int net_context_put(struct net_context *context)

Close and unref a network context.

This releases the context. It is not possible to send or receive data via this context after this call. This is similar as BSD shutdown() function. For legacy compatibility, this function will implicitly decrement the reference count and possibly destroy the context either now or when it reaches a final state.

Return
0 if ok, < 0 if error
Parameters
  • context: The context to be closed.

int net_context_ref(struct net_context *context)

Take a reference count to a net_context, preventing destruction.

Network contexts are not recycled until their reference count reaches zero. Note that this does not prevent any “close” behavior that results from errors or net_context_put. It simply prevents the context from being recycled for further use.

Return
The new reference count
Parameters
  • context: The context on which to increment the reference count

int net_context_unref(struct net_context *context)

Decrement the reference count to a network context.

Decrements the refcount. If it reaches zero, the context will be recycled. Note that this does not cause any network-visible “close” behavior (i.e. future packets to this connection may see TCP RST or ICMP port unreachable responses). See net_context_put() for that.

Return
The new reference count, zero if the context was destroyed
Parameters
  • context: The context on which to decrement the reference count

int net_context_bind(struct net_context *context, const struct sockaddr *addr, socklen_t addrlen)

Assign a socket a local address.

This is similar as BSD bind() function.

Return
0 if ok, < 0 if error
Parameters
  • context: The context to be assigned.
  • addr: Address to assigned.
  • addrlen: Length of the address.

int net_context_listen(struct net_context *context, int backlog)

Mark the context as a listening one.

This is similar as BSD listen() function.

Return
0 if ok, < 0 if error
Parameters
  • context: The context to use.
  • backlog: The size of the pending connections backlog.

int net_context_connect(struct net_context *context, const struct sockaddr *addr, socklen_t addrlen, net_context_connect_cb_t cb, int32_t timeout, void *user_data)

Create a network connection.

The net_context_connect function creates a network connection to the host specified by addr. After the connection is established, the user supplied callback (cb) is executed. cb is called even if the timeout was set to K_FOREVER. cb is not called if the timeout expires. For datagram sockets (SOCK_DGRAM), this function only sets the peer address. This function is similar to the BSD connect() function.

Return
0 on success.
Return
-EINVAL if an invalid parameter is passed as an argument.
Return
-ENOTSUP if the operation is not supported or implemented.
Return
-ETIMEDOUT if the connect operation times out.
Parameters
  • context: The network context.
  • addr: The peer address to connect to.
  • addrlen: Peer address length.
  • cb: Callback function. Set to NULL if not required.
  • timeout: The timeout value for the connection. Possible values:
    • K_NO_WAIT: this function will return immediately,
    • K_FOREVER: this function will block until the connection is established,
    • >0: this function will wait the specified ms.
  • user_data: Data passed to the callback function.

int net_context_accept(struct net_context *context, net_tcp_accept_cb_t cb, int32_t timeout, void *user_data)

Accept a network connection attempt.

Accept a connection being established. This function will return immediately if the timeout is set to K_NO_WAIT. In this case the context will call the supplied callback when ever there is a connection established to this context. This is “a register handler and forget” type of call (async). If the timeout is set to K_FOREVER, the function will wait until the connection is established. Timeout value > 0, will wait as many ms. After the connection is established a caller supplied callback is called. The callback is called even if timeout was set to K_FOREVER, the callback is called before this function will return in this case. The callback is not called if the timeout expires. This is similar as BSD accept() function.

Return
0 if ok, < 0 if error
Parameters
  • context: The context to use.
  • cb: Caller supplied callback function.
  • timeout: Timeout for the connection. Possible values are K_FOREVER, K_NO_WAIT, >0.
  • user_data: Caller supplied user data.

int net_context_send(struct net_buf *buf, net_context_send_cb_t cb, int32_t timeout, void *token, void *user_data)

Send a network buffer to a peer.

This function can be used to send network data to a peer connection. This function will return immediately if the timeout is set to K_NO_WAIT. If the timeout is set to K_FOREVER, the function will wait until the network buffer is sent. Timeout value > 0 will wait as many ms. After the network buffer is sent, a caller supplied callback is called. The callback is called even if timeout was set to K_FOREVER, the callback is called before this function will return in this case. The callback is not called if the timeout expires. For context of type SOCK_DGRAM, the destination address must have been set by the call to net_context_connect(). This is similar as BSD send() function.

Return
0 if ok, < 0 if error
Parameters
  • buf: The network buffer to send.
  • cb: Caller supplied callback function.
  • timeout: Timeout for the connection. Possible values are K_FOREVER, K_NO_WAIT, >0.
  • token: Caller specified value that is passed as is to callback.
  • user_data: Caller supplied user data.

int net_context_sendto(struct net_buf *buf, const struct sockaddr *dst_addr, socklen_t addrlen, net_context_send_cb_t cb, int32_t timeout, void *token, void *user_data)

Send a network buffer to a peer specified by address.

This function can be used to send network data to a peer specified by address. This variant can only be used for datagram connections of type SOCK_DGRAM. This function will return immediately if the timeout is set to K_NO_WAIT. If the timeout is set to K_FOREVER, the function will wait until the network buffer is sent. Timeout value > 0 will wait as many ms. After the network buffer is sent, a caller supplied callback is called. The callback is called even if timeout was set to K_FOREVER, the callback is called before this function will return. The callback is not called if the timeout expires. This is similar as BSD sendto() function.

Return
0 if ok, < 0 if error
Parameters
  • buf: The network buffer to send.
  • dst_addr: Destination address. This will override the address already set in network buffer.
  • addrlen: Length of the address.
  • cb: Caller supplied callback function.
  • timeout: Timeout for the connection. Possible values are K_FOREVER, K_NO_WAIT, >0.
  • token: Caller specified value that is passed as is to callback.
  • user_data: Caller supplied user data.

int net_context_recv(struct net_context *context, net_context_recv_cb_t cb, int32_t timeout, void *user_data)

Receive network data from a peer specified by context.

This function can be used to register a callback function that is called by the network stack when network data has been received for this context. As this function registers a callback, then there is no need to call this function multiple times if timeout is set to K_NO_WAIT. If callback function or user data changes, then the function can be called multiple times to register new values. This function will return immediately if the timeout is set to K_NO_WAIT. If the timeout is set to K_FOREVER, the function will wait until the network buffer is received. Timeout value > 0 will wait as many ms. After the network buffer is received, a caller supplied callback is called. The callback is called even if timeout was set to K_FOREVER, the callback is called before this function will return in this case. The callback is not called if the timeout expires. The timeout functionality can be compiled out if synchronous behaviour is not needed. The sync call logic requires some memory that can be saved if only async way of call is used. If CONFIG_NET_CONTEXT_SYNC_RECV is not set, then the timeout parameter value is ignored. This is similar as BSD recv() function. Note that net_context_bind() should be called before net_context_recv(). Default random port number is assigned to local port. Only bind() will updates connection information from context. If recv() is called before bind() call, it may refuse to bind to a context which already has a connection associated.

Return
0 if ok, < 0 if error
Parameters
  • context: The network context to use.
  • cb: Caller supplied callback function.
  • timeout: Caller supplied timeout. Possible values are K_FOREVER, K_NO_WAIT, >0.
  • user_data: Caller supplied user data.

void net_context_foreach(net_context_cb_t cb, void *user_data)

Go through all the network connections and call callback for each network context.

Parameters
  • cb: User supplied callback function to call.
  • user_data: User specified data.

NET_CONTEXT_IN_USE BIT(0)

Is this context used or not

NET_CONTEXT_FAMILY BIT(4)

The address family, connection type and IP protocol are stored into a bit field to save space.Protocol family of this connection

NET_CONTEXT_TYPE BIT(5)

Type of the connection (datagram / stream)

NET_CONTEXT_PROTO BIT(6)

IP protocol (like UDP or TCP)

NET_CONTEXT_REMOTE_ADDR_SET BIT(7)

Remote address set

NET_CONTEXT_STATE_SHIFT 1
NET_CONTEXT_STATE_MASK 0x03
struct net_context
#include <net_context.h>

Note that we do not store the actual source IP address in the context because the address is already be set in the network interface struct. If there is no such source address there, the packet cannot be sent anyway. This saves 12 bytes / context in IPv6.

Network and application libraries

DHCPv4

enum dhcpv4::net_dhcpv4_state

Current state of DHCPv4 client address negotiation.

Additions removals and reorders in this definition must be reflected within corresponding changes to net_dhcpv4_state_name.

Values:

NET_DHCPV4_INIT
NET_DHCPV4_DISCOVER
NET_DHCPV4_REQUEST
NET_DHCPV4_RENEWAL
NET_DHCPV4_ACK
void net_dhcpv4_start(struct net_if *iface)

Start DHCPv4 client.

Start DHCPv4 client on a given interface. DHCPv4 client will start negotiation for IPv4 address. Once the negotiation is success IPv4 address details will be added to interface.

Parameters
  • iface: A valid pointer on an interface

MQTT 3.1.1

enum mqtt::mqtt_app

MQTT application type

Values:

MQTT_APP_PUBLISHER_SUBSCRIBER

Publisher and Subscriber application

MQTT_APP_PUBLISHER

Publisher only application

MQTT_APP_SUBSCRIBER

Subscriber only application

MQTT_APP_SERVER

MQTT Server

enum mqtt::mqtt_packet

MQTT Packet Type enum.

See MQTT 2.2.1: MQTT Control Packet type

Values:

MQTT_INVALID = 0
MQTT_CONNECT
MQTT_CONNACK
MQTT_PUBLISH
MQTT_PUBACK
MQTT_PUBREC
MQTT_PUBREL
MQTT_PUBCOMP
MQTT_SUBSCRIBE
MQTT_SUBACK
MQTT_UNSUBSCRIBE
MQTT_UNSUBACK
MQTT_PINGREQ
MQTT_PINGRESP
MQTT_DISCONNECT
enum mqtt::mqtt_protocol

MQTT protocol version.

Values:

MQTT_311 = 4
enum mqtt::mqtt_qos

See MQTT 4.3 Quality of Service levels and protocol flows.

Values:

MQTT_QoS0 = 0
MQTT_QoS1
MQTT_QoS2
int mqtt_init(struct mqtt_ctx *ctx, enum mqtt_app app_type)

Initializes the MQTT context structure

Parameters
  • ctx: MQTT context structure
  • app_type: See enum mqtt_app
Return Value
  • 0always.:

int mqtt_tx_connect(struct mqtt_ctx *ctx, struct mqtt_connect_msg *msg)

Sends the MQTT CONNECT message

Parameters
  • ctx: MQTT context structure
  • msg: MQTT CONNECT msg
Return Value
  • 0: on success
  • -EIO:
  • -ENOMEM:
  • -EINVAL:

int mqtt_tx_disconnect(struct mqtt_ctx *ctx)

Send the MQTT DISCONNECT message

Parameters
  • ctx: MQTT context structure
Return Value
  • 0: on success
  • -EIO:
  • -ENOMEM:
  • -EINVAL:

int mqtt_tx_puback(struct mqtt_ctx *ctx, uint16_t id)

Sends the MQTT PUBACK message with the given packet id

Parameters
  • ctx: MQTT context structure
  • id: MQTT Packet Identifier
Return Value
  • 0: on success
  • -EINVAL:
  • -ENOMEM:
  • -EIO:

int mqtt_tx_pubcomp(struct mqtt_ctx *ctx, uint16_t id)

Sends the MQTT PUBCOMP message with the given packet id

Parameters
  • ctx: MQTT context structure
  • id: MQTT Packet Identifier
Return Value
  • 0: on success
  • -EINVAL:
  • -ENOMEM:
  • -EIO:

int mqtt_tx_pubrec(struct mqtt_ctx *ctx, uint16_t id)

Sends the MQTT PUBREC message with the given packet id

Parameters
  • ctx: MQTT context structure
  • id: MQTT Packet Identifier
Return Value
  • 0: on success
  • -EINVAL:
  • -ENOMEM:
  • -EIO:

int mqtt_tx_pubrel(struct mqtt_ctx *ctx, uint16_t id)

Sends the MQTT PUBREL message with the given packet id

Parameters
  • ctx: MQTT context structure
  • id: MQTT Packet Identifier
Return Value
  • 0: on success
  • -EINVAL:
  • -ENOMEM:
  • -EIO:

int mqtt_tx_publish(struct mqtt_ctx *ctx, struct mqtt_publish_msg *msg)

Sends the MQTT PUBLISH message

Parameters
  • ctx: MQTT context structure
  • msg: MQTT PUBLISH msg
Return Value
  • 0: on success
  • -EINVAL:
  • -ENOMEM:
  • -EIO:

int mqtt_tx_pingreq(struct mqtt_ctx *ctx)

Sends the MQTT PINGREQ message

Parameters
  • ctx: MQTT context structure
Return Value
  • 0: on success
  • -EINVAL:
  • -ENOMEM:
  • -EIO:

int mqtt_tx_subscribe(struct mqtt_ctx *ctx, uint16_t pkt_id, uint8_t items, const char *topics[], const enum mqtt_qos qos[])

Sends the MQTT SUBSCRIBE message

Parameters
  • ctx: MQTT context structure
  • pkt_id: Packet identifier for the MQTT SUBSCRIBE msg
  • items: Number of elements in ‘topics’ and ‘qos’ arrays
  • topics: Array of ‘items’ elements containing C strings. For example: {“sensors”, “lights”, “doors”}
  • qos: Array of ‘items’ elements containing MQTT QoS values: MQTT_QoS0, MQTT_QoS1, MQTT_QoS2. For example for the ‘topics’ array above the following QoS may be used: {MQTT_QoS0, MQTT_QoS2, MQTT_QoS1}, indicating that the subscription to ‘lights’ must be done with MQTT_QoS2
Return Value
  • 0: on success
  • -EINVAL:
  • -ENOMEM:
  • -EIO:

int mqtt_tx_unsubscribe(struct mqtt_ctx *ctx, uint16_t pkt_id, uint8_t items, const char *topics[])

Sends the MQTT UNSUBSCRIBE message

Parameters
  • ctx: MQTT context structure
  • pkt_id: Packet identifier for the MQTT UNSUBSCRIBE msg
  • items: Number of elements in the ‘topics’ array
  • topics: Array of ‘items’ elements containing C strings
Return Value
  • 0: on success
  • -EINVAL:
  • -ENOMEM:
  • -EIO:

int mqtt_rx_connack(struct mqtt_ctx *ctx, struct net_buf *rx, int clean_session)

Parses and validates the MQTT CONNACK msg

Parameters
  • ctx: MQTT context structure
  • rx: Data buffer
  • clean_session: MQTT clean session parameter
Return Value
  • 0: on success
  • -EINVAL:

int mqtt_rx_puback(struct mqtt_ctx *ctx, struct net_buf *rx)

Parses and validates the MQTT PUBACK message

Parameters
  • ctx: MQTT context structure
  • rx: Data buffer
Return Value
  • 0: on success
  • -EINVAL:

int mqtt_rx_pubcomp(struct mqtt_ctx *ctx, struct net_buf *rx)

Parses and validates the MQTT PUBCOMP message

Parameters
  • ctx: MQTT context structure
  • rx: Data buffer
Return Value
  • 0: on success
  • -EINVAL:

int mqtt_rx_pubrec(struct mqtt_ctx *ctx, struct net_buf *rx)

Parses and validates the MQTT PUBREC message

Parameters
  • ctx: MQTT context structure
  • rx: Data buffer
Return Value
  • 0: on success
  • -EINVAL:

int mqtt_rx_pubrel(struct mqtt_ctx *ctx, struct net_buf *rx)

Parses and validates the MQTT PUBREL message

Parameters
  • ctx: MQTT context structure
  • rx: Data buffer
Return Value
  • 0: on success
  • -EINVAL:

int mqtt_rx_pingresp(struct mqtt_ctx *ctx, struct net_buf *rx)

Parses the MQTT PINGRESP message

Parameters
  • ctx: MQTT context structure
  • rx: Data buffer
Return Value
  • 0: on success
  • -EINVAL:

int mqtt_rx_suback(struct mqtt_ctx *ctx, struct net_buf *rx)

Parses the MQTT SUBACK message

Parameters
  • ctx: MQTT context structure
  • rx: Data buffer
Return Value
  • 0: on success
  • -EINVAL:

int mqtt_rx_unsuback(struct mqtt_ctx *ctx, struct net_buf *rx)

Parses the MQTT UNSUBACK message

Parameters
  • ctx: MQTT context structure
  • rx: Data buffer
Return Value
  • 0: on success
  • -EINVAL:

int mqtt_rx_publish(struct mqtt_ctx *ctx, struct net_buf *rx)

Parses the MQTT PUBLISH message

Parameters
  • ctx: MQTT context structure
  • rx: Data buffer
Return Value
  • 0: on success
  • -EINVAL:
  • -ENOMEM:

struct mqtt_ctx
#include <mqtt.h>

MQTT context structure

Context structure for the MQTT high-level API with support for QoS.

This API is designed for asynchronous operation, so callbacks are executed when some events must be addressed outside the MQTT routines. Those events are triggered by the reception or transmission of MQTT messages and are defined by the MQTT v3.1.1 spec, see:

http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/mqtt-v3.1.1.html

For example, assume that Zephyr is operating as a MQTT_APP_SUBSCRIBER, so it may receive the MQTT PUBLISH and MQTT PUBREL (QoS2) messages. Once the messages are parsed and validated, the publish_rx callback is executed.

Internally, the publish_rx callback must store the mqtt_publish_msg message when a MQTT PUBLISH msg is received. When a MQTT PUBREL message is received, the application must evaluate if the PUBREL’s Packet Identifier matches a previous received MQTT PUBLISH message. In this case, the user may provide a collection of mqtt_publish_msg structs (array of structs) to store those messages.

NOTE: The application (and not the API) is in charge of keeping track of the state of the received and sent messages.

DNS Client

enum dns_client::dns_query_type

DNS query type enum

Values:

DNS_QUERY_TYPE_A = 1
DNS_QUERY_TYPE_AAAA = 28
int dns_init(struct dns_context *ctx)

DNS resolver initialization routine

This routine must be called before any other dns routine.

Parameters
  • ctx: DNS Client structure
Return Value
  • 0new: versions may return error codes.

int dns_resolve(struct dns_context *ctx)

Retrieves the IP addresses associated to the domain name ‘client->name’.

This routine obtains the IP addresses associated to the domain name ‘client->name’. The DNS server is specified by the sockaddr structure inside ‘client’. Depending on the DNS server used, one or more IP addresses may be recovered by this routine.

NOTE: You can use an IPv6 DNS server to look-up for IPv4 addresses or an IPv4 server to look-up for IPv6 address. Domain name services are not tied to any specific routing or transport technology.

Parameters
  • ctx: DNS Client structure
Return Value
  • 0: on success. The number of returned addresses (client->items) may be less than the one reported by the DNS server. However, this situation is considered a success because we are ‘resolving’ the ‘name’. Workaround: increase ‘client->elements’.
  • -EIO: on network error.
  • -EINVAL: if an invalid parameter was passed as an argument to this routine. This value is also returned if the application received a malformed packet from the DNS server.
  • -ENOMEM: if there are no buffers available.

struct dns_context
#include <dns_client.h>

DNS client context structure

union

An array of IPv4 or IPv6 address

Public Members