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.

Network core helpers

group net_core

Network core library.

Defines

NET_DBG(...)
NET_ERR(...)
NET_INFO(...)
NET_WARN(...)
NET_ASSERT(...)
NET_ASSERT_INFO(...)
NET_STACK_GET_NAME(pretty, name, sfx)
NET_STACK_INFO(...)
NET_STACK_INFO_ADDR(...)
NET_STACK_DEFINE(pretty_name, name, orig, size)
NET_STACK_ARRAY_DEFINE(pretty_name, name, orig, size, nmemb)
NET_STACK_DEFINE_EMBEDDED(name, size)
NET_TC_TX_COUNT
NET_TC_RX_COUNT
NET_TC_COUNT

Enums

enum net_verdict

Net Verdict.

Values:

NET_OK
NET_CONTINUE

Packet has been taken care of

NET_DROP

Packet has not been touched, other part should decide about its fate

Functions

int net_recv_data(struct net_if *iface, struct net_pkt *pkt)
int net_send_data(struct net_pkt *pkt)

Send data to network.

Send data to network. This should not be used normally by applications as it requires that the pktfer and fragments are properly constructed.

Return
0 if ok, <0 if error. If <0 is returned, then the caller needs to unref the pkt in order to avoid memory leak.
Parameters
  • pkt: Network packet.

Network buffers

group net_buf

Network buffer library.

Defines

NET_BUF_SIMPLE_DEFINE(_name, _size)

Define a net_buf_simple stack variable.

This is a helper macro which is used to define a net_buf_simple object on the stack.

Parameters
  • _name: Name of the net_buf_simple object.
  • _size: Maximum data storage for the buffer.

NET_BUF_SIMPLE_DEFINE_STATIC(_name, _size)

Define a static net_buf_simple variable.

This is a helper macro which is used to define a static net_buf_simple object.

Parameters
  • _name: Name of the net_buf_simple object.
  • _size: Maximum data storage for the buffer.

NET_BUF_SIMPLE(_size)

Define a net_buf_simple stack variable and get a pointer to it.

This is a helper macro which is used to define a net_buf_simple object on the stack and the get a pointer to it as follows:

struct net_buf_simple *my_buf = NET_BUF_SIMPLE(10);

After creating the object it needs to be initialized by calling net_buf_simple_init().

Return
Pointer to stack-allocated net_buf_simple object.
Parameters
  • _size: Maximum data storage for the buffer.

NET_BUF_FRAGS

Flag indicating that the buffer has associated fragments. Only used internally by the buffer handling code while the buffer is inside a FIFO, meaning this never needs to be explicitly set or unset by the net_buf API user. As long as the buffer is outside of a FIFO, i.e. in practice always for the user for this API, the buf->frags pointer should be used instead.

NET_BUF_EXTERNAL_DATA

Flag indicating that the buffer’s associated data pointer, points to externally allocated memory. Therefore once ref goes down to zero, the pointed data will not need to be deallocated. This never needs to be explicitly set or unet by the net_buf API user. Such net_buf is exclusively instantiated via net_buf_alloc_with_data() function. Reference count mechanism however will behave the same way, and ref count going to 0 will free the net_buf but no the data pointer in it.

NET_BUF_POOL_INITIALIZER(_pool, _alloc, _bufs, _count, _destroy)
NET_BUF_POOL_HEAP_DEFINE(_name, _count, _destroy)

Define a new pool for buffers using the heap for the data.

Defines a net_buf_pool struct and the necessary memory storage (array of structs) for the needed amount of buffers. After this, the buffers can be accessed from the pool through net_buf_alloc. The pool is defined as a static variable, so if it needs to be exported outside the current module this needs to happen with the help of a separate pointer rather than an extern declaration.

The data payload of the buffers will be allocated from the heap using k_malloc, so CONFIG_HEAP_MEM_POOL_SIZE must be set to a positive value. This kind of pool does not support blocking on the data allocation, so the timeout passed to net_buf_alloc will be always treated as K_NO_WAIT when trying to allocate the data. This means that allocation failures, i.e. NULL returns, must always be handled cleanly.

If provided with a custom destroy callback, this callback is responsible for eventually calling net_buf_destroy() to complete the process of returning the buffer to the pool.

Parameters
  • _name: Name of the pool variable.
  • _count: Number of buffers in the pool.
  • _destroy: Optional destroy callback when buffer is freed.

NET_BUF_POOL_FIXED_DEFINE(_name, _count, _data_size, _destroy)

Define a new pool for buffers based on fixed-size data.

Defines a net_buf_pool struct and the necessary memory storage (array of structs) for the needed amount of buffers. After this, the buffers can be accessed from the pool through net_buf_alloc. The pool is defined as a static variable, so if it needs to be exported outside the current module this needs to happen with the help of a separate pointer rather than an extern declaration.

The data payload of the buffers will be allocated from a byte array of fixed sized chunks. This kind of pool does not support blocking on the data allocation, so the timeout passed to net_buf_alloc will be always treated as K_NO_WAIT when trying to allocate the data. This means that allocation failures, i.e. NULL returns, must always be handled cleanly.

If provided with a custom destroy callback, this callback is responsible for eventually calling net_buf_destroy() to complete the process of returning the buffer to the pool.

Parameters
  • _name: Name of the pool variable.
  • _count: Number of buffers in the pool.
  • _data_size: Maximum data payload per buffer.
  • _destroy: Optional destroy callback when buffer is freed.

NET_BUF_POOL_VAR_DEFINE(_name, _count, _data_size, _destroy)

Define a new pool for buffers with variable size payloads.

Defines a net_buf_pool struct and the necessary memory storage (array of structs) for the needed amount of buffers. After this, the buffers can be accessed from the pool through net_buf_alloc. The pool is defined as a static variable, so if it needs to be exported outside the current module this needs to happen with the help of a separate pointer rather than an extern declaration.

The data payload of the buffers will be based on a memory pool from which variable size payloads may be allocated.

If provided with a custom destroy callback, this callback is responsible for eventually calling net_buf_destroy() to complete the process of returning the buffer to the pool.

Parameters
  • _name: Name of the pool variable.
  • _count: Number of buffers in the pool.
  • _data_size: Total amount of memory available for data payloads.
  • _destroy: Optional destroy callback when buffer is freed.

NET_BUF_POOL_DEFINE(_name, _count, _size, _ud_size, _destroy)

Define a new pool for buffers.

Defines a net_buf_pool struct and the necessary memory storage (array of structs) for the needed amount of buffers. After this,the buffers can be accessed from the pool through net_buf_alloc. The pool is defined as a static variable, so if it needs to be exported outside the current module this needs to happen with the help of a separate pointer rather than an extern declaration.

If provided with a custom destroy callback this callback is responsible for eventually calling net_buf_destroy() to complete the process of returning the buffer to the pool.

Parameters
  • _name: Name of the pool variable.
  • _count: Number of buffers in the pool.
  • _size: Maximum data size for each buffer.
  • _ud_size: Amount of user data space to reserve.
  • _destroy: Optional destroy callback when buffer is freed.

net_buf_alloc(_pool, _timeout)
net_buf_reserve(buf, reserve)

Initialize buffer with the given headroom.

Initializes a buffer with a given headroom. The buffer is not expected to contain any data when this API is called.

Parameters
  • buf: Buffer to initialize.
  • reserve: How much headroom to reserve.

net_buf_add(buf, len)

Prepare data to be added at the end of the buffer.

Increments the data length of a buffer to account for more data at the end.

Return
The original tail of the buffer.
Parameters
  • buf: Buffer to update.
  • len: Number of bytes to increment the length with.

net_buf_add_mem(buf, mem, len)

Copy bytes from memory to the end of the buffer.

Copies the given number of bytes to the end of the buffer. Increments the data length of the buffer to account for more data at the end.

Return
The original tail of the buffer.
Parameters
  • buf: Buffer to update.
  • mem: Location of data to be added.
  • len: Length of data to be added

net_buf_add_u8(buf, val)

Add (8-bit) byte at the end of the buffer.

Adds a byte at the end of the buffer. Increments the data length of the buffer to account for more data at the end.

Return
Pointer to the value added
Parameters
  • buf: Buffer to update.
  • val: byte value to be added.

net_buf_add_le16(buf, val)

Add 16-bit value at the end of the buffer.

Adds 16-bit value in little endian format at the end of buffer. Increments the data length of a buffer to account for more data at the end.

Parameters
  • buf: Buffer to update.
  • val: 16-bit value to be added.

net_buf_add_be16(buf, val)

Add 16-bit value at the end of the buffer.

Adds 16-bit value in big endian format at the end of buffer. Increments the data length of a buffer to account for more data at the end.

Parameters
  • buf: Buffer to update.
  • val: 16-bit value to be added.

net_buf_add_le32(buf, val)

Add 32-bit value at the end of the buffer.

Adds 32-bit value in little endian format at the end of buffer. Increments the data length of a buffer to account for more data at the end.

Parameters
  • buf: Buffer to update.
  • val: 32-bit value to be added.

net_buf_add_be32(buf, val)

Add 32-bit value at the end of the buffer.

Adds 32-bit value in big endian format at the end of buffer. Increments the data length of a buffer to account for more data at the end.

Parameters
  • buf: Buffer to update.
  • val: 32-bit value to be added.

net_buf_push(buf, len)

Push data to the beginning of the buffer.

Modifies the data pointer and buffer length to account for more data in the beginning of the buffer.

Return
The new beginning of the buffer data.
Parameters
  • buf: Buffer to update.
  • len: Number of bytes to add to the beginning.

net_buf_push_le16(buf, val)

Push 16-bit value to the beginning of the buffer.

Adds 16-bit value in little endian format to the beginning of the buffer.

Parameters
  • buf: Buffer to update.
  • val: 16-bit value to be pushed to the buffer.

net_buf_push_be16(buf, val)

Push 16-bit value to the beginning of the buffer.

Adds 16-bit value in little endian format to the beginning of the buffer.

Parameters
  • buf: Buffer to update.
  • val: 16-bit value to be pushed to the buffer.

net_buf_push_u8(buf, val)

Push 8-bit value to the beginning of the buffer.

Adds 8-bit value the beginning of the buffer.

Parameters
  • buf: Buffer to update.
  • val: 8-bit value to be pushed to the buffer.

net_buf_pull(buf, len)

Remove data from the beginning of the buffer.

Removes data from the beginning of the buffer by modifying the data pointer and buffer length.

Return
New beginning of the buffer data.
Parameters
  • buf: Buffer to update.
  • len: Number of bytes to remove.

net_buf_pull_u8(buf)

Remove a 8-bit value from the beginning of the buffer.

Same idea as with net_buf_pull(), but a helper for operating on 8-bit values.

Return
The 8-bit removed value
Parameters
  • buf: A valid pointer on a buffer.

net_buf_pull_le16(buf)

Remove and convert 16 bits from the beginning of the buffer.

Same idea as with net_buf_pull(), but a helper for operating on 16-bit little endian data.

Return
16-bit value converted from little endian to host endian.
Parameters
  • buf: A valid pointer on a buffer.

net_buf_pull_be16(buf)

Remove and convert 16 bits from the beginning of the buffer.

Same idea as with net_buf_pull(), but a helper for operating on 16-bit big endian data.

Return
16-bit value converted from big endian to host endian.
Parameters
  • buf: A valid pointer on a buffer.

net_buf_pull_le32(buf)

Remove and convert 32 bits from the beginning of the buffer.

Same idea as with net_buf_pull(), but a helper for operating on 32-bit little endian data.

Return
32-bit value converted from little endian to host endian.
Parameters
  • buf: A valid pointer on a buffer.

net_buf_pull_be32(buf)

Remove and convert 32 bits from the beginning of the buffer.

Same idea as with net_buf_pull(), but a helper for operating on 32-bit big endian data.

Return
32-bit value converted from big endian to host endian.
Parameters
  • buf: A valid pointer on a buffer

net_buf_tailroom(buf)

Check buffer tailroom.

Check how much free space there is at the end of the buffer.

Return
Number of bytes available at the end of the buffer.
Parameters
  • buf: A valid pointer on a buffer

net_buf_headroom(buf)

Check buffer headroom.

Check how much free space there is in the beginning of the buffer.

buf A valid pointer on a buffer

Return
Number of bytes available in the beginning of the buffer.

net_buf_tail(buf)

Get the tail pointer for a buffer.

Get a pointer to the end of the data in a buffer.

Return
Tail pointer for the buffer.
Parameters
  • buf: Buffer.

Typedefs

typedef net_buf_allocator_cb

Network buffer allocator callback.

The allocator callback is called when net_buf_append_bytes needs to allocate a new net_buf.

Return
pointer to allocated net_buf or NULL on error.
Parameters
  • timeout: Affects the action taken should the net buf pool be empty. If K_NO_WAIT, then return immediately. If K_FOREVER, then wait as long as necessary. Otherwise, wait up to the specified number of milliseconds before timing out.
  • user_data: The user data given in net_buf_append_bytes call.

Functions

static void net_buf_simple_init(struct net_buf_simple *buf, size_t reserve_head)

Initialize a net_buf_simple object.

This needs to be called after creating a net_buf_simple object using the NET_BUF_SIMPLE macro.

Parameters
  • buf: Buffer to initialize.
  • reserve_head: Headroom to reserve.

static void net_buf_simple_reset(struct net_buf_simple *buf)

Reset buffer.

Reset buffer data so it can be reused for other purposes.

Parameters
  • buf: Buffer to reset.

void *net_buf_simple_add(struct net_buf_simple *buf, size_t len)

Prepare data to be added at the end of the buffer.

Increments the data length of a buffer to account for more data at the end.

Return
The original tail of the buffer.
Parameters
  • buf: Buffer to update.
  • len: Number of bytes to increment the length with.

void *net_buf_simple_add_mem(struct net_buf_simple *buf, const void *mem, size_t len)

Copy bytes from memory to the end of the buffer.

Copies the given number of bytes to the end of the buffer. Increments the data length of the buffer to account for more data at the end.

Return
The original tail of the buffer.
Parameters
  • buf: Buffer to update.
  • mem: Location of data to be added.
  • len: Length of data to be added

u8_t *net_buf_simple_add_u8(struct net_buf_simple *buf, u8_t val)

Add (8-bit) byte at the end of the buffer.

Adds a byte at the end of the buffer. Increments the data length of the buffer to account for more data at the end.

Return
Pointer to the value added
Parameters
  • buf: Buffer to update.
  • val: byte value to be added.

void net_buf_simple_add_le16(struct net_buf_simple *buf, u16_t val)

Add 16-bit value at the end of the buffer.

Adds 16-bit value in little endian format at the end of buffer. Increments the data length of a buffer to account for more data at the end.

Parameters
  • buf: Buffer to update.
  • val: 16-bit value to be added.

void net_buf_simple_add_be16(struct net_buf_simple *buf, u16_t val)

Add 16-bit value at the end of the buffer.

Adds 16-bit value in big endian format at the end of buffer. Increments the data length of a buffer to account for more data at the end.

Parameters
  • buf: Buffer to update.
  • val: 16-bit value to be added.

void net_buf_simple_add_le32(struct net_buf_simple *buf, u32_t val)

Add 32-bit value at the end of the buffer.

Adds 32-bit value in little endian format at the end of buffer. Increments the data length of a buffer to account for more data at the end.

Parameters
  • buf: Buffer to update.
  • val: 32-bit value to be added.

void net_buf_simple_add_be32(struct net_buf_simple *buf, u32_t val)

Add 32-bit value at the end of the buffer.

Adds 32-bit value in big endian format at the end of buffer. Increments the data length of a buffer to account for more data at the end.

Parameters
  • buf: Buffer to update.
  • val: 32-bit value to be added.

void *net_buf_simple_push(struct net_buf_simple *buf, size_t len)

Push data to the beginning of the buffer.

Modifies the data pointer and buffer length to account for more data in the beginning of the buffer.

Return
The new beginning of the buffer data.
Parameters
  • buf: Buffer to update.
  • len: Number of bytes to add to the beginning.

void net_buf_simple_push_le16(struct net_buf_simple *buf, u16_t val)

Push 16-bit value to the beginning of the buffer.

Adds 16-bit value in little endian format to the beginning of the buffer.

Parameters
  • buf: Buffer to update.
  • val: 16-bit value to be pushed to the buffer.

void net_buf_simple_push_be16(struct net_buf_simple *buf, u16_t val)

Push 16-bit value to the beginning of the buffer.

Adds 16-bit value in big endian format to the beginning of the buffer.

Parameters
  • buf: Buffer to update.
  • val: 16-bit value to be pushed to the buffer.

void net_buf_simple_push_u8(struct net_buf_simple *buf, u8_t val)

Push 8-bit value to the beginning of the buffer.

Adds 8-bit value the beginning of the buffer.

Parameters
  • buf: Buffer to update.
  • val: 8-bit value to be pushed to the buffer.

void *net_buf_simple_pull(struct net_buf_simple *buf, size_t len)

Remove data from the beginning of the buffer.

Removes data from the beginning of the buffer by modifying the data pointer and buffer length.

Return
New beginning of the buffer data.
Parameters
  • buf: Buffer to update.
  • len: Number of bytes to remove.

u8_t net_buf_simple_pull_u8(struct net_buf_simple *buf)

Remove a 8-bit value from the beginning of the buffer.

Same idea as with net_buf_simple_pull(), but a helper for operating on 8-bit values.

Return
The 8-bit removed value
Parameters
  • buf: A valid pointer on a buffer.

u16_t net_buf_simple_pull_le16(struct net_buf_simple *buf)

Remove and convert 16 bits from the beginning of the buffer.

Same idea as with net_buf_simple_pull(), but a helper for operating on 16-bit little endian data.

Return
16-bit value converted from little endian to host endian.
Parameters
  • buf: A valid pointer on a buffer.

u16_t net_buf_simple_pull_be16(struct net_buf_simple *buf)

Remove and convert 16 bits from the beginning of the buffer.

Same idea as with net_buf_simple_pull(), but a helper for operating on 16-bit big endian data.

Return
16-bit value converted from big endian to host endian.
Parameters
  • buf: A valid pointer on a buffer.

u32_t net_buf_simple_pull_le32(struct net_buf_simple *buf)

Remove and convert 32 bits from the beginning of the buffer.

Same idea as with net_buf_simple_pull(), but a helper for operating on 32-bit little endian data.

Return
32-bit value converted from little endian to host endian.
Parameters
  • buf: A valid pointer on a buffer.

u32_t net_buf_simple_pull_be32(struct net_buf_simple *buf)

Remove and convert 32 bits from the beginning of the buffer.

Same idea as with net_buf_simple_pull(), but a helper for operating on 32-bit big endian data.

Return
32-bit value converted from big endian to host endian.
Parameters
  • buf: A valid pointer on a buffer.

static u8_t *net_buf_simple_tail(struct net_buf_simple *buf)

Get the tail pointer for a buffer.

Get a pointer to the end of the data in a buffer.

Return
Tail pointer for the buffer.
Parameters
  • buf: Buffer.

size_t net_buf_simple_headroom(struct net_buf_simple *buf)

Check buffer headroom.

Check how much free space there is in the beginning of the buffer.

buf A valid pointer on a buffer

Return
Number of bytes available in the beginning of the buffer.

size_t net_buf_simple_tailroom(struct net_buf_simple *buf)

Check buffer tailroom.

Check how much free space there is at the end of the buffer.

Return
Number of bytes available at the end of the buffer.
Parameters
  • buf: A valid pointer on a buffer

static void net_buf_simple_save(struct net_buf_simple *buf, struct net_buf_simple_state *state)

Save the parsing state of a buffer.

Saves the parsing state of a buffer so it can be restored later.

Parameters
  • buf: Buffer from which the state should be saved.
  • state: Storage for the state.

static void net_buf_simple_restore(struct net_buf_simple *buf, struct net_buf_simple_state *state)

Restore the parsing state of a buffer.

Restores the parsing state of a buffer from a state previously stored by net_buf_simple_save().

Parameters
  • buf: Buffer to which the state should be restored.
  • state: Stored state.

struct net_buf_pool *net_buf_pool_get(int id)

Looks up a pool based on its ID.

Return
Pointer to pool.
Parameters
  • id: Pool ID (e.g. from buf->pool_id).

int net_buf_id(struct net_buf *buf)

Get a zero-based index for a buffer.

This function will translate a buffer into a zero-based index, based on its placement in its buffer pool. This can be useful if you want to associate an external array of meta-data contexts with the buffers of a pool.

Return
Zero-based index for the buffer.
Parameters
  • buf: Network buffer.

struct net_buf *net_buf_alloc_fixed(struct net_buf_pool *pool, s32_t timeout)

Allocate a new buffer from a pool.

Allocate a new buffer from a pool.

Return
New buffer or NULL if out of buffers.
Parameters
  • pool: Which pool to allocate the buffer from.
  • timeout: Affects the action taken should the pool be empty. If K_NO_WAIT, then return immediately. If K_FOREVER, then wait as long as necessary. Otherwise, wait up to the specified number of milliseconds before timing out. Note that some types of data allocators do not support blocking (such as the HEAP type). In this case it’s still possible for net_buf_alloc() to fail (return NULL) even if it was given K_FOREVER.

struct net_buf *net_buf_alloc_len(struct net_buf_pool *pool, size_t size, s32_t timeout)

Allocate a new buffer from a pool.

Allocate a new buffer from a pool.

Return
New buffer or NULL if out of buffers.
Parameters
  • pool: Which pool to allocate the buffer from.
  • size: Amount of data the buffer must be able to fit.
  • timeout: Affects the action taken should the pool be empty. If K_NO_WAIT, then return immediately. If K_FOREVER, then wait as long as necessary. Otherwise, wait up to the specified number of milliseconds before timing out. Note that some types of data allocators do not support blocking (such as the HEAP type). In this case it’s still possible for net_buf_alloc() to fail (return NULL) even if it was given K_FOREVER.

struct net_buf *net_buf_alloc_with_data(struct net_buf_pool *pool, void *data, size_t size, s32_t timeout)

Allocate a new buffer from a pool but with external data pointer.

Allocate a new buffer from a pool, where the data pointer comes from the user and not from the pool.

Return
New buffer or NULL if out of buffers.
Parameters
  • pool: Which pool to allocate the buffer from.
  • data: External data pointer
  • size: Amount of data the pointed data buffer if able to fit.
  • timeout: Affects the action taken should the pool be empty. If K_NO_WAIT, then return immediately. If K_FOREVER, then wait as long as necessary. Otherwise, wait up to the specified number of milliseconds before timing out. Note that some types of data allocators do not support blocking (such as the HEAP type). In this case it’s still possible for net_buf_alloc() to fail (return NULL) even if it was given K_FOREVER.

struct net_buf *net_buf_get(struct k_fifo *fifo, s32_t timeout)

Get a buffer from a FIFO.

Get buffer from a FIFO.

Return
New buffer or NULL if the FIFO is empty.
Parameters
  • fifo: Which FIFO to take the buffer from.
  • timeout: Affects the action taken should the FIFO be empty. If K_NO_WAIT, then return immediately. If K_FOREVER, then wait as long as necessary. Otherwise, wait up to the specified number of milliseconds before timing out.

static void net_buf_destroy(struct net_buf *buf)

Destroy buffer from custom destroy callback.

This helper is only intended to be used from custom destroy callbacks. If no custom destroy callback is given to NET_BUF_POOL_*_DEFINE() then there is no need to use this API.

Parameters
  • buf: Buffer to destroy.

void net_buf_reset(struct net_buf *buf)

Reset buffer.

Reset buffer data and flags so it can be reused for other purposes.

Parameters
  • buf: Buffer to reset.

void net_buf_simple_reserve(struct net_buf_simple *buf, size_t reserve)

Initialize buffer with the given headroom.

Initializes a buffer with a given headroom. The buffer is not expected to contain any data when this API is called.

Parameters
  • buf: Buffer to initialize.
  • reserve: How much headroom to reserve.

void net_buf_slist_put(sys_slist_t *list, struct net_buf *buf)

Put a buffer into a list.

Put a buffer to the end of a list. If the buffer contains follow-up fragments this function will take care of inserting them as well into the list.

Parameters
  • list: Which list to append the buffer to.
  • buf: Buffer.

struct net_buf *net_buf_slist_get(sys_slist_t *list)

Get a buffer from a list.

Get buffer from a list. If the buffer had any fragments, these will automatically be recovered from the list as well and be placed to the buffer’s fragment list.

Return
New buffer or NULL if the FIFO is empty.
Parameters
  • list: Which list to take the buffer from.

void net_buf_put(struct k_fifo *fifo, struct net_buf *buf)

Put a buffer into a FIFO.

Put a buffer to the end of a FIFO. If the buffer contains follow-up fragments this function will take care of inserting them as well into the FIFO.

Parameters
  • fifo: Which FIFO to put the buffer to.
  • buf: Buffer.

void net_buf_unref(struct net_buf *buf)

Decrements the reference count of a buffer.

Decrements the reference count of a buffer and puts it back into the pool if the count reaches zero.

Parameters
  • buf: A valid pointer on a buffer

struct net_buf *net_buf_ref(struct net_buf *buf)

Increment the reference count of a buffer.

Return
the buffer newly referenced
Parameters
  • buf: A valid pointer on a buffer

struct net_buf *net_buf_clone(struct net_buf *buf, s32_t timeout)

Duplicate buffer.

Duplicate given buffer including any data and headers currently stored.

Return
Duplicated buffer or NULL if out of buffers.
Parameters
  • buf: A valid pointer on a buffer
  • timeout: Affects the action taken should the pool be empty. If K_NO_WAIT, then return immediately. If K_FOREVER, then wait as long as necessary. Otherwise, wait up to the specified number of milliseconds before timing out.

static void *net_buf_user_data(const struct net_buf *buf)

Get a pointer to the user data of a buffer.

Return
Pointer to the user data of the buffer.
Parameters
  • buf: A valid pointer on a buffer

struct net_buf *net_buf_frag_last(struct net_buf *frags)

Find the last fragment in the fragment list.

Return
Pointer to last fragment in the list.

void net_buf_frag_insert(struct net_buf *parent, struct net_buf *frag)

Insert a new fragment to a chain of bufs.

Insert a new fragment into the buffer fragments list after the parent.

Note: This function takes ownership of the fragment reference so the caller is not required to unref.

Parameters
  • parent: Parent buffer/fragment.
  • frag: Fragment to insert.

struct net_buf *net_buf_frag_add(struct net_buf *head, struct net_buf *frag)

Add a new fragment to the end of a chain of bufs.

Append a new fragment into the buffer fragments list.

Note: This function takes ownership of the fragment reference so the caller is not required to unref.

Return
New head of the fragment chain. Either head (if head was non-NULL) or frag (if head was NULL).
Parameters
  • head: Head of the fragment chain.
  • frag: Fragment to add.

struct net_buf *net_buf_frag_del(struct net_buf *parent, struct net_buf *frag)

Delete existing fragment from a chain of bufs.

Return
Pointer to the buffer following the fragment, or NULL if it had no further fragments.
Parameters
  • parent: Parent buffer/fragment, or NULL if there is no parent.
  • frag: Fragment to delete.

int net_buf_linearize(void *dst, size_t dst_len, struct net_buf *src, u16_t offset, u16_t len)

Copy len bytes from src starting from offset to dst buffer.

This routine assumes that dst is large enough to store len bytes starting from offset at src.

Return
number of bytes copied if everything is ok
Return
-ENOMEM on error
Parameters
  • dst: Destination buffer
  • dst_len: Destination buffer max length
  • src: Source buffer that may be fragmented
  • offset: Starting point to copy from
  • len: Number of bytes to copy

u16_t net_buf_append_bytes(struct net_buf *buf, u16_t len, const u8_t *value, s32_t timeout, net_buf_allocator_cb allocate_cb, void *user_data)

Append data to a list of net_buf.

Append data to a net_buf. If there is not enough space in the net_buf then more net_buf will be added, unless there are no free net_buf and timeout occurs.

Return
Length of data actually added. This may be less than input length if other timeout than K_FOREVER was used, and there were no free fragments in a pool to accommodate all data.
Parameters
  • buf: Network buffer.
  • len: Total length of input data
  • value: Data to be added
  • timeout: Timeout is passed to the net_buf allocator callback.
  • allocate_cb: When a new net_buf is required, use this callback.
  • user_data: A user data pointer to be supplied to the allocate_cb. This pointer is can be anything from a mem_pool or a net_pkt, the logic is left up to the allocate_cb function.

static struct net_buf *net_buf_skip(struct net_buf *buf, u16_t len)

Skip N number of bytes in a net_buf.

Skip N number of bytes starting from fragment’s offset. If the total length of data is placed in multiple fragments, this function will skip from all fragments until it reaches N number of bytes. Any fully skipped buffers are removed from the net_buf list.

Return
Pointer to the fragment or NULL and pos is 0 after successful skip, NULL and pos is 0xffff otherwise.
Parameters
  • buf: Network buffer.
  • len: Total length of data to be skipped.

static size_t net_buf_frags_len(struct net_buf *buf)

Calculate amount of bytes stored in fragments.

Calculates the total amount of data stored in the given buffer and the fragments linked to it.

Return
Number of bytes in the buffer and its fragments.
Parameters
  • buf: Buffer to start off with.

Variables

const struct net_buf_data_alloc net_buf_heap_alloc
const struct net_buf_data_cb net_buf_fixed_cb
const struct net_buf_data_cb net_buf_var_cb
struct net_buf_simple
#include <buf.h>

Simple network buffer representation.

This is a simpler variant of the net_buf object (in fact net_buf uses net_buf_simple internally). It doesn’t provide any kind of reference counting, user data, dynamic allocation, or in general the ability to pass through kernel objects such as FIFOs.

The main use of this is for scenarios where the meta-data of the normal net_buf isn’t needed and causes too much overhead. This could be e.g. when the buffer only needs to be allocated on the stack or when the access to and lifetime of the buffer is well controlled and constrained.

struct net_buf_simple_state
#include <buf.h>

Parsing state of a buffer.

This is used for temporarily storing the parsing state of a buffer while giving control of the parsing to a routine which we don’t control.

struct net_buf
#include <buf.h>

Network buffer representation.

This struct is used to represent network buffers. Such buffers are normally defined through the NET_BUF_POOL_*_DEFINE() APIs and allocated using the net_buf_alloc() API.

Network packet management

group net_pkt

Network packet management library.

Defines

NET_PKT_SLAB_DEFINE(name, count)

Create a net_pkt slab.

A net_pkt slab is used to store meta-information about network packets. It must be coupled with a data fragment pool (:c:macro:NET_PKT_DATA_POOL_DEFINE) used to store the actual packet data. The macro can be used by an application to define additional custom per-context TX packet slabs (see :c:func:net_context_setup_pools).

Parameters
  • name: Name of the slab.
  • count: Number of net_pkt in this slab.

NET_PKT_TX_SLAB_DEFINE(name, count)
NET_PKT_DATA_POOL_DEFINE(name, count)

Create a data fragment net_buf pool.

A net_buf pool is used to store actual data for network packets. It must be coupled with a net_pkt slab (:c:macro:NET_PKT_SLAB_DEFINE) used to store the packet meta-information. The macro can be used by an application to define additional custom per-context TX packet pools (see :c:func:net_context_setup_pools).

Parameters
  • name: Name of the pool.
  • count: Number of net_buf in this pool.

net_pkt_print_frags(...)
net_pkt_print(...)

Functions

struct net_pkt *net_pkt_get_reserve(struct k_mem_slab *slab, u16_t reserve_head, s32_t timeout)

Get packet from the given packet slab.

Get network packet from the specific packet slab.

Return
Network packet if successful, NULL otherwise.
Parameters
  • slab: Network packet slab.
  • reserve_head: How many bytes to reserve for headroom.
  • timeout: Affects the action taken should the net pkt slab be empty. If K_NO_WAIT, then return immediately. If K_FOREVER, then wait as long as necessary. Otherwise, wait up to the specified number of milliseconds before timing out.

struct net_pkt *net_pkt_get_rx(struct net_context *context, s32_t timeout)

Get packet from the RX packet slab.

Get network packet from RX packet slab. You must have network context before able to use this function.

Return
Network packet if successful, NULL otherwise.
Parameters
  • context: Network context that will be related to this packet.
  • timeout: Affects the action taken should the net pkt slab be empty. If K_NO_WAIT, then return immediately. If K_FOREVER, then wait as long as necessary. Otherwise, wait up to the specified number of milliseconds before timing out.

struct net_pkt *net_pkt_get_tx(struct net_context *context, s32_t timeout)

Get packet from the TX packets slab.

Get network packet from TX packet slab. You must have network context before able to use this function.

Return
Network packet if successful, NULL otherwise.
Parameters
  • context: Network context that will be related to this packet.
  • timeout: Affects the action taken should the net pkt slab be empty. If K_NO_WAIT, then return immediately. If K_FOREVER, then wait as long as necessary. Otherwise, wait up to the specified number of milliseconds before timing out.

struct net_buf *net_pkt_get_data(struct net_context *context, s32_t timeout)

Get buffer from the DATA buffers pool.

Get network buffer from DATA buffer pool. You must have network context before able to use this function.

Return
Network buffer if successful, NULL otherwise.
Parameters
  • context: Network context that will be related to this buffer.
  • timeout: Affects the action taken should the net buf pool be empty. If K_NO_WAIT, then return immediately. If K_FOREVER, then wait as long as necessary. Otherwise, wait up to the specified number of milliseconds before timing out.

struct net_pkt *net_pkt_get_reserve_rx(u16_t reserve_head, s32_t timeout)

Get RX packet from slab but also reserve headroom for potential headers.

Normally this version is not useful for applications but is mainly used by network fragmentation code.

Return
Network packet if successful, NULL otherwise.
Parameters
  • reserve_head: How many bytes to reserve for headroom.
  • timeout: Affects the action taken should the net pkt slab be empty. If K_NO_WAIT, then return immediately. If K_FOREVER, then wait as long as necessary. Otherwise, wait up to the specified number of milliseconds before timing out.

struct net_pkt *net_pkt_get_reserve_tx(u16_t reserve_head, s32_t timeout)

Get TX packet from slab but also reserve headroom for potential headers.

Normally this version is not useful for applications but is mainly used by network fragmentation code.

Return
Network packet if successful, NULL otherwise.
Parameters
  • reserve_head: How many bytes to reserve for headroom.
  • timeout: Affects the action taken should the net pkt slab be empty. If K_NO_WAIT, then return immediately. If K_FOREVER, then wait as long as necessary. Otherwise, wait up to the specified number of milliseconds before timing out.

struct net_buf *net_pkt_get_reserve_rx_data(u16_t reserve_head, s32_t timeout)

Get RX DATA buffer from pool but also reserve headroom for potential headers. Normally you should use net_pkt_get_frag() instead.

Normally this version is not useful for applications but is mainly used by network fragmentation code.

Return
Network buffer if successful, NULL otherwise.
Parameters
  • reserve_head: How many bytes to reserve for headroom.
  • timeout: Affects the action taken should the net buf pool be empty. If K_NO_WAIT, then return immediately. If K_FOREVER, then wait as long as necessary. Otherwise, wait up to the specified number of milliseconds before timing out.

struct net_buf *net_pkt_get_reserve_tx_data(u16_t reserve_head, s32_t timeout)

Get TX DATA buffer from pool but also reserve headroom for potential headers. Normally you should use net_pkt_get_frag() instead.

Normally this version is not useful for applications but is mainly used by network fragmentation code.

Return
Network buffer if successful, NULL otherwise.
Parameters
  • reserve_head: How many bytes to reserve for headroom.
  • timeout: Affects the action taken should the net buf pool be empty. If K_NO_WAIT, then return immediately. If K_FOREVER, then wait as long as necessary. Otherwise, wait up to the specified number of milliseconds before timing out.

struct net_buf *net_pkt_get_frag(struct net_pkt *pkt, s32_t timeout)

Get a data fragment that might be from user specific buffer pool or from global DATA pool.

Return
Network buffer if successful, NULL otherwise.
Parameters
  • pkt: Network packet.
  • timeout: Affects the action taken should the net buf pool be empty. If K_NO_WAIT, then return immediately. If K_FOREVER, then wait as long as necessary. Otherwise, wait up to the specified number of milliseconds before timing out.

void net_pkt_unref(struct net_pkt *pkt)

Place packet back into the available packets slab.

Releases the packet to other use. This needs to be called by application after it has finished with the packet.

Parameters
  • pkt: Network packet to release.

struct net_pkt *net_pkt_ref(struct net_pkt *pkt)

Increase the packet ref count.

Mark the packet to be used still.

Return
Network packet if successful, NULL otherwise.
Parameters
  • pkt: Network packet to ref.

struct net_buf *net_pkt_frag_ref(struct net_buf *frag)

Increase the packet fragment ref count.

Mark the fragment to be used still.

Return
a pointer on the referenced Network fragment.
Parameters
  • frag: Network fragment to ref.

void net_pkt_frag_unref(struct net_buf *frag)

Decrease the packet fragment ref count.

Parameters
  • frag: Network fragment to unref.

struct net_buf *net_pkt_frag_del(struct net_pkt *pkt, struct net_buf *parent, struct net_buf *frag)

Delete existing fragment from a packet.

Return
Pointer to the following fragment, or NULL if it had no further fragments.
Parameters
  • pkt: Network packet from which frag belongs to.
  • parent: parent fragment of frag, or NULL if none.
  • frag: Fragment to delete.

void net_pkt_frag_add(struct net_pkt *pkt, struct net_buf *frag)

Add a fragment to a packet at the end of its fragment list.

Parameters
  • pkt: pkt Network packet where to add the fragment
  • frag: Fragment to add

void net_pkt_frag_insert(struct net_pkt *pkt, struct net_buf *frag)

Insert a fragment to a packet at the beginning of its fragment list.

Parameters
  • pkt: pkt Network packet where to insert the fragment
  • frag: Fragment to insert

struct net_buf *net_pkt_copy(struct net_pkt *pkt, size_t amount, size_t reserve, s32_t timeout)

Copy a packet fragment list while reserving some extra space in destination buffer before a copy.

Return
New fragment list if successful, NULL otherwise.
Parameters
  • pkt: Network packet.
  • amount: Max amount of data to be copied.
  • reserve: Amount of extra data (this is not link layer header) in the first data fragment that is returned. The function will copy the original buffer right after the reserved bytes in the first destination fragment.
  • timeout: Affects the action taken should the net buf pool be empty. If K_NO_WAIT, then return immediately. If K_FOREVER, then wait as long as necessary. Otherwise, wait up to the specified number of milliseconds before timing out.

static struct net_buf *net_pkt_copy_all(struct net_pkt *pkt, size_t reserve, s32_t timeout)

Copy a packet fragment list while reserving some extra space in destination buffer before a copy.

Return
New fragment list if successful, NULL otherwise.
Parameters
  • pkt: Network packet.
  • reserve: Amount of extra data (this is not link layer header) in the first data fragment that is returned. The function will copy the original buffer right after the reserved bytes in the first destination fragment.
  • timeout: Affects the action taken should the net buf pool be empty. If K_NO_WAIT, then return immediately. If K_FOREVER, then wait as long as necessary. Otherwise, wait up to the specified number of milliseconds before timing out.

int net_frag_linear_copy(struct net_buf *dst, struct net_buf *src, u16_t offset, u16_t len)

Copy len bytes from src starting from offset to dst.

This routine assumes that dst is formed of one fragment with enough space to store len bytes starting from offset at src.

Return
0 on success
Return
-ENOMEM on error
Parameters
  • dst: Destination buffer
  • src: Source buffer that may be fragmented
  • offset: Starting point to copy from
  • len: Number of bytes to copy

int net_frag_linearize(u8_t *dst, size_t dst_len, struct net_pkt *src, u16_t offset, u16_t len)

Copy len bytes from src starting from offset to dst buffer.

This routine assumes that dst is large enough to store len bytes starting from offset at src.

Return
number of bytes copied if everything is ok
Return
-ENOMEM on error
Parameters
  • dst: Destination buffer
  • dst_len: Destination buffer max length
  • src: Source buffer that may be fragmented
  • offset: Starting point to copy from
  • len: Number of bytes to copy

bool net_pkt_compact(struct net_pkt *pkt)

Compact the fragment list of a packet.

After this there is no more any free space in individual fragments.

Return
True if compact success, False otherwise.
Parameters
  • pkt: Network packet.

u16_t net_pkt_append(struct net_pkt *pkt, u16_t len, const u8_t *data, s32_t timeout)

Append data to fragment list of a packet.

Append data to last fragment. If there is not enough space in last fragment then more data fragments will be added, unless there are no free fragments and timeout occurs.

Return
Length of data actually added. This may be less than input length if other timeout than K_FOREVER was used, and there were no free fragments in a pool to accommodate all data.
Parameters
  • pkt: Network packet.
  • len: Total length of input data
  • data: Data to be added
  • timeout: Affects the action taken should the net buf pool be empty. If K_NO_WAIT, then return immediately. If K_FOREVER, then wait as long as necessary. Otherwise, wait up to the specified number of milliseconds before timing out.

static bool net_pkt_append_all(struct net_pkt *pkt, u16_t len, const u8_t *data, s32_t timeout)

Append all data to fragment list of a packet (or fail)

Append data to last fragment. If there is not enough space in last fragment then more data fragments will be added. Return unsuccessful status if there are no free fragments to accommodate all data and timeout occurs.

Return
True if all the data is placed at end of fragment list, false otherwise (in which case packet may contain incomplete input data).
Parameters
  • pkt: Network packet.
  • len: Total length of input data
  • data: Data to be added
  • timeout: Affects the action taken should the net buf pool be empty. If K_NO_WAIT, then return immediately. If K_FOREVER, then wait as long as necessary. Otherwise, wait up to the specified number of milliseconds before timing out.

u16_t net_pkt_append_memset(struct net_pkt *pkt, u16_t len, const u8_t data, s32_t timeout)

Append fixed bytes of data to fragment list of a packet.

Append data to last fragment. If there is not enough space in last fragment then more data fragments will be added, unless there are no free fragments and timeout occurs.

Return
Length of data actually added. This may be less than input length if other timeout than K_FOREVER was used, and there were no free fragments in a pool to accommodate all data.
Parameters
  • pkt: Network packet.
  • len: Total length of input data
  • data: Byte to initialize fragment with
  • timeout: Affects the action taken should the net buf pool be empty. If K_NO_WAIT, then return immediately. If K_FOREVER, then wait as long as necessary. Otherwise, wait up to the specified number of milliseconds before timing out.

static bool net_pkt_append_u8(struct net_pkt *pkt, u8_t data)

Append u8_t data to last fragment in fragment list of a packet.

Append data to last fragment. If there is not enough space in last fragment then new data fragment will be created and will be added to fragment list. Caller has to take care of endianness if needed.

Return
True if all the data is placed at end of fragment list, False otherwise (In-case of false pkt might contain input data in the process of placing into fragments).
Parameters
  • pkt: Network packet.
  • data: Data to be added

static bool net_pkt_append_be16(struct net_pkt *pkt, u16_t data)

Append u16_t data to last fragment in fragment list of a packet.

Append data to last fragment. If there is not enough space in last fragment then new data fragment will be created and will be added to fragment list. Caller has to take care of endianness if needed.

Return
True if all the data is placed at end of fragment list, False otherwise (In-case of false pkt might contain input data in the process of placing into fragments).
Parameters
  • pkt: Network packet.
  • data: Data to be added

static bool net_pkt_append_be32(struct net_pkt *pkt, u32_t data)

Append u32_t data to last fragment in fragment list of a packet.

Append data to last fragment. If there is not enough space in last fragment then new data fragment will be created and will be added to fragment list. Caller has to take care of endianness if needed.

Return
True if all the data is placed at end of fragment list, False otherwise (In-case of false pkt might contain input data in the process of placing into fragments).
Parameters
  • pkt: Network packet.
  • data: Data to be added

static bool net_pkt_append_le32(struct net_pkt *pkt, u32_t data)

Append u32_t data to last fragment in fragment list.

Append data to last fragment. If there is not enough space in last fragment then new data fragment will be created and will be added to fragment list. Convert data to LE.

Return
True if all the data is placed at end of fragment list, False otherwise (In-case of false pkt might contain input data in the process of placing into fragments).
Parameters
  • pkt: Network packet fragment list.
  • data: Data to be added

static bool net_pkt_append_u8_timeout(struct net_pkt *pkt, u8_t data, s32_t timeout)

Append u8_t data to last fragment in fragment list of a packet.

Append data to last fragment. If there is not enough space in last fragment then new data fragment will be created and will be added to fragment list. Caller has to take care of endianness if needed.

Return
True if all the data is placed at end of fragment list, False otherwise (In-case of false pkt might contain input data in the process of placing into fragments).
Parameters
  • pkt: Network packet.
  • data: Data to be added
  • timeout: Timeout for buffer allocations

static bool net_pkt_append_be16_timeout(struct net_pkt *pkt, u16_t data, s32_t timeout)

Append u16_t data to last fragment in fragment list of a packet.

Append data to last fragment. If there is not enough space in last fragment then new data fragment will be created and will be added to fragment list. Caller has to take care of endianness if needed.

Return
True if all the data is placed at end of fragment list, False otherwise (In-case of false pkt might contain input data in the process of placing into fragments).
Parameters
  • pkt: Network packet.
  • data: Data to be added
  • timeout: Timeout for buffer allocations

static bool net_pkt_append_be32_timeout(struct net_pkt *pkt, u32_t data, s32_t timeout)

Append u32_t data to last fragment in fragment list of a packet.

Append data to last fragment. If there is not enough space in last fragment then new data fragment will be created and will be added to fragment list. Caller has to take care of endianness if needed.

Return
True if all the data is placed at end of fragment list, False otherwise (In-case of false pkt might contain input data in the process of placing into fragments).
Parameters
  • pkt: Network packet.
  • data: Data to be added
  • timeout: Timeout for buffer allocations

static bool net_pkt_append_le32_timeout(struct net_pkt *pkt, u32_t data, s32_t timeout)

Append u32_t data to last fragment in fragment list.

Append data to last fragment. If there is not enough space in last fragment then new data fragment will be created and will be added to fragment list. Convert data to LE.

Return
True if all the data is placed at end of fragment list, False otherwise (In-case of false pkt might contain input data in the process of placing into fragments).
Parameters
  • pkt: Network packet fragment list.
  • data: Data to be added
  • timeout: Timeout for buffer allocations

struct net_buf *net_frag_read(struct net_buf *frag, u16_t offset, u16_t *pos, u16_t len, u8_t *data)

Get data from buffer.

Get N number of bytes starting from fragment’s offset. If the total length of data is placed in multiple fragments, this function will read from all fragments until it reaches N number of bytes. Caller has to take care of endianness if needed.

Return
Pointer to the fragment or NULL and pos is 0 after successful read, NULL and pos is 0xffff otherwise.
Parameters
  • frag: Network buffer fragment.
  • offset: Offset of input buffer.
  • pos: Pointer to position of offset after reading n number of bytes, this is with respect to return buffer(fragment).
  • len: Total length of data to be read.
  • data: Data will be copied here.

static struct net_buf *net_frag_skip(struct net_buf *frag, u16_t offset, u16_t *pos, u16_t len)

Skip N number of bytes while reading buffer.

Skip N number of bytes starting from fragment’s offset. If the total length of data is placed in multiple fragments, this function will skip from all fragments until it reaches N number of bytes. This function is useful when unwanted data (e.g. reserved or not supported data in message) is part of fragment and we want to skip it.

Return
Pointer to the fragment or NULL and pos is 0 after successful skip, NULL and pos is 0xffff otherwise.
Parameters
  • frag: Network buffer fragment.
  • offset: Offset of input buffer.
  • pos: Pointer to position of offset after reading n number of bytes, this is with respect to return buffer(fragment).
  • len: Total length of data to be read.

static struct net_buf *net_frag_read_u8(struct net_buf *frag, u16_t offset, u16_t *pos, u8_t *value)

Get a byte value from fragmented buffer.

Return
Pointer to fragment after successful read, NULL otherwise (if pos is 0, NULL is not a failure case).
Parameters
  • frag: Network buffer fragment.
  • offset: Offset of input buffer.
  • pos: Pointer to position of offset after reading 2 bytes, this is with respect to return buffer(fragment).
  • value: Value is returned

struct net_buf *net_frag_read_be16(struct net_buf *frag, u16_t offset, u16_t *pos, u16_t *value)

Get 16 bit big endian value from fragmented buffer.

Return
Pointer to fragment after successful read, NULL otherwise (if pos is 0, NULL is not a failure case).
Parameters
  • frag: Network buffer fragment.
  • offset: Offset of input buffer.
  • pos: Pointer to position of offset after reading 2 bytes, this is with respect to return buffer(fragment).
  • value: Value is returned

struct net_buf *net_frag_read_be32(struct net_buf *frag, u16_t offset, u16_t *pos, u32_t *value)

Get 32 bit big endian value from fragmented buffer.

Return
Pointer to fragment after successful read, NULL otherwise (if pos is 0, NULL is not a failure case).
Parameters
  • frag: Network buffer fragment.
  • offset: Offset of input buffer.
  • pos: Pointer to position of offset after reading 4 bytes, this is with respect to return buffer(fragment).
  • value: Value is returned

struct net_buf *net_pkt_write(struct net_pkt *pkt, struct net_buf *frag, u16_t offset, u16_t *pos, u16_t len, u8_t *data, s32_t timeout)

Write data to an arbitrary offset in fragments list of a packet.

Write data to an arbitrary offset in a series of fragments. Offset is based on fragment ‘size’ and calculates from input fragment starting position.

Size in this context refers the fragment full size without link layer header part. The fragment might have user written data in it, the amount of such data is stored in frag->len variable (the frag->len is always <= frag->size). If using this API, the tailroom in the fragments will be taken into use.

If offset is more than already allocated length in fragment, then empty space or extra empty fragments is created to reach proper offset. If there is any data present on input fragment offset, then it will be ‘overwritten’. Use net_pkt_insert() api if you don’t want to overwrite.

Offset is calculated from starting point of data area in input fragment. e.g. Pkt(Tx/Rx) - Frag1 - Frag2 - Frag3 - Frag4 (Assume FRAG DATA SIZE is 100 bytes after link layer header)

1) net_pkt_write(pkt, frag2, 20, &pos, 20, data, K_FOREVER) In this case write starts from “frag2->data + 20”, returns frag2, pos = 40

2) net_pkt_write(pkt, frag1, 150, &pos, 60, data, K_FOREVER) In this case write starts from “frag2->data + 50” returns frag3, pos = 10

3) net_pkt_write(pkt, frag1, 350, &pos, 30, data, K_FOREVER) In this case write starts from “frag4->data + 50” returns frag4, pos = 80

4) net_pkt_write(pkt, frag2, 110, &pos, 90, data, K_FOREVER) In this case write starts from “frag3->data + 10” returns frag4, pos = 0

5) net_pkt_write(pkt, frag4, 110, &pos, 20, data, K_FOREVER) In this case write creates new data fragment and starts from “frag5->data + 10” returns frag5, pos = 30

If input argument frag is NULL, it will create new data fragment and append at the end of fragment list.

Return
Pointer to the fragment and position (*pos) where write ended, NULL and pos is 0xffff otherwise.
Parameters
  • pkt: Network packet.
  • frag: Network buffer fragment.
  • offset: Offset
  • pos: Position of offset after write completed (this will be relative to return fragment)
  • len: Length of the data to be written.
  • data: Data to be written
  • timeout: Affects the action taken should the net buf pool be empty. If K_NO_WAIT, then return immediately. If K_FOREVER, then wait as long as necessary. Otherwise, wait up to the specified number of milliseconds before timing out.

static struct net_buf *net_pkt_write_u8(struct net_pkt *pkt, struct net_buf *frag, u16_t offset, u16_t *pos, u8_t data)
static struct net_buf *net_pkt_write_be16(struct net_pkt *pkt, struct net_buf *frag, u16_t offset, u16_t *pos, u16_t data)
static struct net_buf *net_pkt_write_be32(struct net_pkt *pkt, struct net_buf *frag, u16_t offset, u16_t *pos, u32_t data)
static struct net_buf *net_pkt_write_u8_timeout(struct net_pkt *pkt, struct net_buf *frag, u16_t offset, u16_t *pos, u8_t data, s32_t timeout)
static struct net_buf *net_pkt_write_be16_timeout(struct net_pkt *pkt, struct net_buf *frag, u16_t offset, u16_t *pos, u16_t data, s32_t timeout)
static struct net_buf *net_pkt_write_be32_timeout(struct net_pkt *pkt, struct net_buf *frag, u16_t offset, u16_t *pos, u32_t data, s32_t timeout)
bool net_pkt_insert(struct net_pkt *pkt, struct net_buf *frag, u16_t offset, u16_t len, u8_t *data, s32_t timeout)

Insert data at an arbitrary offset in a series of fragments.

Insert data at an arbitrary offset in a series of fragments. Offset is based on fragment length (only user written data length, any tailroom in fragments does not come to consideration unlike net_pkt_write()) and calculates from input fragment starting position. If the data pointer is NULL, insert a sequence of zeros with the given length.

Offset examples can be considered from net_pkt_write() api. If the offset is more than already allocated fragments length then it is an error case.

Return
True on success, False otherwise.
Parameters
  • pkt: Network packet.
  • frag: Network buffer fragment.
  • offset: Offset of fragment where insertion will start.
  • len: Length of the data to be inserted.
  • data: Data to be inserted, can be NULL.
  • timeout: Affects the action taken should the net buf pool be empty. If K_NO_WAIT, then return immediately. If K_FOREVER, then wait as long as necessary. Otherwise, wait up to the specified number of milliseconds before timing out.

static bool net_pkt_insert_u8(struct net_pkt *pkt, struct net_buf *frag, u16_t offset, u8_t data)
static bool net_pkt_insert_be16(struct net_pkt *pkt, struct net_buf *frag, u16_t offset, u16_t data)
static bool net_pkt_insert_be32(struct net_pkt *pkt, struct net_buf *frag, u16_t offset, u32_t data)
static bool net_pkt_insert_u8_timeout(struct net_pkt *pkt, struct net_buf *frag, u16_t offset, u8_t data, s32_t timeout)
static bool net_pkt_insert_be16_timeout(struct net_pkt *pkt, struct net_buf *frag, u16_t offset, u16_t data, s32_t timeout)
static bool net_pkt_insert_be32_timeout(struct net_pkt *pkt, struct net_buf *frag, u16_t offset, u32_t data, s32_t timeout)
int net_pkt_split(struct net_pkt *pkt, struct net_buf *frag, u16_t offset, struct net_buf **rest, s32_t timeout)

Split a fragment into two parts at arbitrary offset.

This will split packet into two parts. Original packet will be modified. Offset is relative position with input fragment. Input fragment contains first part of the split. Rest of the fragment chain is in “rest” parameter provided by caller.

Return
0 on success, <0 otherwise.
Parameters
  • pkt: Network packet
  • frag: Original network buffer fragment which is to be split.
  • offset: Offset relative to input fragment.
  • rest: Rest of the fragment chain after split.
  • timeout: Affects the action taken should the net buf pool be empty. If K_NO_WAIT, then return immediately. If K_FOREVER, then wait as long as necessary. Otherwise, wait up to the specified number of milliseconds before timing out.

int net_pkt_pull(struct net_pkt *pkt, u16_t offset, u16_t len)

Remove data from the packet at arbitrary offset.

This will remove the data from arbitrary offset. Original packet will be modified.

Return
0 on success, <0 otherwise
Parameters
  • pkt: Network packet
  • offset: Arbitrary offset to packet
  • len: Number of bytes to be removed

struct net_buf *net_frag_get_pos(struct net_pkt *pkt, u16_t offset, u16_t *pos)

Return the fragment and offset within it according to network packet offset.

This is typically used to get the protocol header pointer when we know the offset. According to this information, the corresponding fragment and position within that fragment is returned.

Return
Pointer to the fragment where the the offset is located or NULL if there is not enough bytes in the packet
Parameters
  • pkt: Network packet
  • offset: Offset of desired location in network packet. For example, if we want to know where UDP header is located after the IPv6 header, the offset could have a value of sizeof(struct net_ipv6_hdr). Note that this is a simplified example that does not take into account the possible IPv6 extension headers.
  • pos: Pointer to position within result fragment corresponding to offset param. For example, if the IPv6 header is split between two fragments, then if we want to know the start of UDP header, the returned pos variable would indicate how many bytes from second fragment the UDP header starts.

struct net_pkt *net_pkt_clone(struct net_pkt *pkt, s32_t timeout)

Clone pkt and its fragment chain.

Return
NULL if error, clone fragment chain otherwise.
Parameters
  • pkt: Original pkt to be cloned
  • timeout: Timeout to wait for free net_buf

void net_pkt_get_info(struct k_mem_slab **rx, struct k_mem_slab **tx, struct net_buf_pool **rx_data, struct net_buf_pool **tx_data)

Get information about predefined RX, TX and DATA pools.

Parameters
  • rx: Pointer to RX pool is returned.
  • tx: Pointer to TX pool is returned.
  • rx_data: Pointer to RX DATA pool is returned.
  • tx_data: Pointer to TX DATA pool is returned.

int net_pkt_get_src_addr(struct net_pkt *pkt, struct sockaddr *addr, socklen_t addrlen)

Get source socket address.

Return
0 on success, <0 otherwise.
Parameters
  • pkt: Network packet
  • addr: Source socket address
  • addrlen: The length of source socket address

int net_pkt_get_dst_addr(struct net_pkt *pkt, struct sockaddr *addr, socklen_t addrlen)

Get destination socket address.

Return
0 on success, <0 otherwise.
Parameters
  • pkt: Network packet
  • addr: Destination socket address
  • addrlen: The length of destination socket address

IPv4/IPv6 primitives and helpers

group ip_4_6

IPv4/IPv6 primitives and helpers.

Defines

NET_VLAN_TAG_UNSPEC
PF_UNSPEC

Protocol families

PF_INET
PF_INET6
AF_UNSPEC

Address families.

AF_INET
AF_INET6
ntohs(x)
ntohl(x)
ntohll(x)
htons(x)
htonl(x)
htonll(x)
NET_SOCKADDR_MAX_SIZE
NET_SOCKADDR_PTR_MAX_SIZE
IN6ADDR_ANY_INIT
IN6ADDR_LOOPBACK_INIT
INET6_ADDRSTRLEN
NET_IPV6_ADDR_LEN
NET_IPV4_ADDR_LEN
INADDR_ANY
INADDR_ANY_INIT
NET_IPV6_MTU
NET_IPV4_MTU
NET_IPV6_NEXTHDR_HBHO

IPv6 extension headers types

NET_IPV6_NEXTHDR_DESTO
NET_IPV6_NEXTHDR_ROUTING
NET_IPV6_NEXTHDR_FRAG
NET_IPV6_NEXTHDR_NONE
NET_UDPH_LEN
NET_TCPH_LEN
NET_ICMPH_LEN
NET_IPV6H_LEN
NET_ICMPV6H_LEN
NET_IPV6UDPH_LEN
NET_IPV6TCPH_LEN
NET_IPV6ICMPH_LEN
NET_IPV6_FRAGH_LEN
NET_IPV4H_LEN
NET_ICMPV4H_LEN
NET_IPV4UDPH_LEN
NET_IPV4TCPH_LEN
NET_IPV4ICMPH_LEN
net_ipaddr_copy(dest, src)

Copy an IPv4 or IPv6 address.

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

Typedefs

typedef unsigned short int sa_family_t
typedef size_t socklen_t

Enums

enum net_ip_protocol

Protocol numbers from IANA

Values:

IPPROTO_ICMP = 1
IPPROTO_TCP = 6
IPPROTO_UDP = 17
IPPROTO_ICMPV6 = 58
enum net_ip_protocol_secure

Values:

IPPROTO_TLS_1_0 = 256
IPPROTO_TLS_1_1 = 257
IPPROTO_TLS_1_2 = 258
IPPROTO_DTLS_1_0 = 272
IPPROTO_DTLS_1_2 = 273
enum net_sock_type

Socket type

Values:

SOCK_STREAM = 1
SOCK_DGRAM
enum net_priority

Network packet priority settings described in IEEE 802.1Q Annex I.1

Values:

NET_PRIORITY_BK = 1
NET_PRIORITY_BE = 0
NET_PRIORITY_EE = 2
NET_PRIORITY_CA = 3
NET_PRIORITY_VI = 4
NET_PRIORITY_VO = 5
NET_PRIORITY_IC = 6
NET_PRIORITY_NC = 7
enum 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
NET_ADDR_OVERRIDABLE
enum 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

Functions

static const 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 u8_t *addr1, const u8_t *addr2, u8_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

static bool net_is_ipv4_ll_addr(const struct in_addr *addr)

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

Return
True if it is, false otherwise.
Parameters
  • addr: A valid pointer on an 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(const 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, u16_t addr0, u16_t addr1, u16_t addr2, u16_t addr3, u16_t addr4, u16_t addr5, u16_t addr6, u16_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: Buffer for IP address as a null terminated string
  • size: Number of bytes available in the buffer

bool net_ipaddr_parse(const char *str, size_t str_len, struct sockaddr *addr)

Parse a string that contains either IPv4 or IPv6 address and optional port, and store the information in user supplied sockaddr struct.

Syntax of the IP address string: 192.0.2.1:80 192.0.2.42

[2001:db8::2] 2001:db::42 Note that the str_len parameter is used to restrict the amount of characters that are checked. If the string does not contain port number, then the port number in sockaddr is not modified.

Return
True if parsing could be done, false otherwise.
Parameters
  • str: String that contains the IP address.
  • str_len: Length of the string to be parsed.
  • addr: Pointer to user supplied struct sockaddr.

static s32_t net_tcp_seq_cmp(u32_t seq1, u32_t seq2)

Compare TCP sequence numbers.

This function compares TCP sequence numbers, accounting for wraparound effects.

Return
< 0 if seq1 < seq2, 0 if seq1 == seq2, > 0 if seq > seq2
Parameters
  • seq1: First sequence number
  • seq2: Seconds sequence number

static bool net_tcp_seq_greater(u32_t seq1, u32_t seq2)

Check that one TCP sequence number is greater.

This is convenience function on top of net_tcp_seq_cmp().

Return
True if seq > seq2
Parameters
  • seq1: First sequence number
  • seq2: Seconds sequence number

int net_bytes_from_str(u8_t *buf, int buf_len, const char *src)

Convert a string of hex values to array of bytes.

The syntax of the string is “ab:02:98:fa:42:01”

Return
0 if ok, <0 if error
Parameters
  • buf: Pointer to memory where the bytes are written.
  • buf_len: Length of the memory area.
  • src: String of bytes.

int net_tx_priority2tc(enum net_priority prio)

Convert Tx network packet priority to traffic class so we can place the packet into correct Tx queue.

Return
Tx traffic class that handles that priority network traffic.
Parameters
  • prio: Network priority

int net_rx_priority2tc(enum net_priority prio)

Convert Rx network packet priority to traffic class so we can place the packet into correct Rx queue.

Return
Rx traffic class that handles that priority network traffic.
Parameters
  • prio: Network priority

static enum net_priority net_vlan2priority(u8_t priority)

Convert network packet VLAN priority to network packet priority so we can place the packet into correct queue.

Return
Network priority
Parameters
  • priority: VLAN priority

static u8_t net_priority2vlan(enum net_priority priority)

Convert network packet priority to network packet VLAN priority.

Return
VLAN priority (PCP)
Parameters
  • priority: Packet priority

Variables

const struct in6_addr in6addr_any
const struct in6_addr in6addr_loopback
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

group net_if

Network Interface abstraction layer.

Defines

NET_IF_MAX_CONFIGS
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_ipv6_select_src_iface(...)
net_if_ipv4_select_src_iface(...)
NET_IF_DHCPV4_INIT
NET_IF_CONFIG_INIT
NET_IF_GET_NAME(dev_name, sfx)
NET_IF_DEV_GET_NAME(dev_name, sfx)
NET_IF_GET(dev_name, sfx)
NET_IF_INIT(dev_name, sfx, _l2, _mtu, _num_configs)
NET_IF_OFFLOAD_INIT(dev_name, sfx, _mtu)
NET_DEVICE_INIT(dev_name, drv_name, init_fn, data, cfg_info, prio, api, l2, l2_ctx_type, mtu)
NET_DEVICE_OFFLOAD_INIT(dev_name, drv_name, init_fn, data, cfg_info, prio, api, mtu)
NET_DEVICE_INIT_INSTANCE(dev_name, drv_name, instance, init_fn, data, cfg_info, prio, api, l2, l2_ctx_type, 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)

Typedefs

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

Parameters
  • struct net_if *iface: A pointer to a struct net_if to which the the net_pkt 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 to user data or NULL

Enums

enum [anonymous]

Values:

NET_IF_UP
NET_IF_POINTOPOINT
NET_IF_PROMISC
NET_IF_NUM_FLAGS

Functions

enum net_verdict net_if_send_data(struct net_if *iface, struct net_pkt *pkt)

Send a packet through a net iface.

return verdict about the packet

Parameters
  • iface: Pointer to a network interface structure
  • pkt: Pointer to a net packet to send

static const struct net_l2 *const net_if_l2(struct net_if *iface)

Get a pointer to the interface L2.

Return
a pointer to the iface L2
Parameters
  • iface: a valid pointer to a network interface structure

enum net_verdict net_if_recv_data(struct net_if *iface, struct net_pkt *pkt)

Input a packet through a net iface.

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

static u16_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 to the destination IPv6 address or NULL if not relevant

static void *net_if_l2_data(struct net_if *iface)

Get a pointer to the interface L2 private data.

Return
a pointer to the iface 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 to the device driver instance
Parameters
  • iface: Pointer to a network interface structure

void net_if_queue_tx(struct net_if *iface, struct net_pkt *pkt)

Queue a packet to the net interface TX queue.

Parameters
  • iface: Pointer to a network interface structure
  • pkt: Pointer to a net packet to queue

Get an network interface’s link address.

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

static struct net_if_config *net_if_get_config(struct net_if *iface)

Return network configuration for this network interface.

Return
Pointer to configuration
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 to a u8_t buffer representing the address
  • len: length of the address buffer
  • type: network bearer type of this link address

static u16_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, u16_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 struct net_if_config *net_if_config_get(struct net_if *iface)

Get network interface IP config.

Return
NULL if not found or pointer to correct config settings.
Parameters
  • iface: Interface to use.

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.

struct net_if *net_if_get_first_by_type(const struct net_l2 *l2)

Get the first network interface according to its type.

Return
First network interface of a given type or NULL if no such interfaces was found.
Parameters
  • l2: Layer 2 type of the network interface.

struct net_if *net_if_select_src_iface(const struct sockaddr *dst)

Get a network interface that should be used when sending IPv6 or IPv4 network data to destination.

Return
Pointer to network interface to use. Note that the function will return the default network interface if the best network interface is not found.
Parameters
  • dst: IPv6 or IPv4 destination address

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

bool net_if_need_calc_rx_checksum(struct net_if *iface)

Check if received network packet checksum calculation can be avoided or not. For example many ethernet devices support network packet offloading in which case the IP stack does not need to calculate the checksum.

Return
True if checksum needs to be calculated, false otherwise.
Parameters
  • iface: Network interface

bool net_if_need_calc_tx_checksum(struct net_if *iface)

Check if network packet checksum calculation can be avoided or not when sending the packet. For example many ethernet devices support network packet offloading in which case the IP stack does not need to calculate the checksum.

Return
True if checksum needs to be calculated, false otherwise.
Parameters
  • iface: Network interface

struct net_if *net_if_get_by_index(u8_t index)

Get interface according to index.

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

u8_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

static bool net_if_is_up(struct net_if *iface)

Check if interface is up.

Return
True if interface is up, False if it is down.
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

int net_if_set_promisc(struct net_if *iface)

Set network interface into promiscuous mode.

Note that not all network technologies will support this.

Return
0 on success, <0 if error
Parameters
  • iface: Pointer to network interface

void net_if_unset_promisc(struct net_if *iface)

Set network interface into normal mode.

Parameters
  • iface: Pointer to network interface

bool net_if_is_promisc(struct net_if *iface)

Check if promiscuous mode is set or not.

Return
True if interface is in promisc mode, False if interface is not in in promiscuous mode.
Parameters
  • iface: Pointer to network interface

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_ip
#include <net_if.h>

Network interface IP address configuration.

struct net_if_config
#include <net_if.h>

IP and other configuration related data for network interface.

struct net_traffic_class
#include <net_if.h>

Network traffic class.

Traffic classes are used when sending or receiving data that is classified with different priorities. So some traffic can be marked as high priority and it will be sent or received first. There is always at least one work queue in the system for Rx and Tx. Each network packet that is transmitted or received goes through a work queue thread that will transmit it.

struct net_if_dev
#include <net_if.h>

Network Interface Device structure.

Used to handle a network interface on top of a device driver instance. There can be many net_if_dev 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_dev should be instantiated by

struct net_if
#include <net_if.h>

Network Interface structure.

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

#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

group net_mgmt

Network Management.

Defines

NET_EVENT_IF_DOWN
NET_EVENT_IF_UP
NET_EVENT_IPV6_ADDR_ADD
NET_EVENT_IPV6_ADDR_DEL
NET_EVENT_IPV6_MADDR_ADD
NET_EVENT_IPV6_MADDR_DEL
NET_EVENT_IPV6_PREFIX_ADD
NET_EVENT_IPV6_PREFIX_DEL
NET_EVENT_IPV6_MCAST_JOIN
NET_EVENT_IPV6_MCAST_LEAVE
NET_EVENT_IPV6_ROUTER_ADD
NET_EVENT_IPV6_ROUTER_DEL
NET_EVENT_IPV6_ROUTE_ADD
NET_EVENT_IPV6_ROUTE_DEL
NET_EVENT_IPV6_DAD_SUCCEED
NET_EVENT_IPV6_DAD_FAILED
NET_EVENT_IPV6_NBR_ADD
NET_EVENT_IPV6_NBR_DEL
NET_EVENT_IPV4_ADDR_ADD
NET_EVENT_IPV4_ADDR_DEL
NET_EVENT_IPV4_ROUTER_ADD
NET_MGMT_EVENT_MASK

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

NET_MGMT_ON_IFACE_MASK
NET_MGMT_LAYER_MASK
NET_MGMT_SYNC_EVENT_MASK
NET_MGMT_LAYER_CODE_MASK
NET_MGMT_COMMAND_MASK
NET_MGMT_EVENT_BIT
NET_MGMT_IFACE_BIT
NET_MGMT_SYNC_EVENT_BIT
NET_MGMT_LAYER(_layer)
NET_MGMT_LAYER_CODE(_code)
NET_MGMT_EVENT(mgmt_request)
NET_MGMT_ON_IFACE(mgmt_request)
NET_MGMT_EVENT_SYNCHRONOUS(mgmt_request)
NET_MGMT_GET_LAYER(mgmt_request)
NET_MGMT_GET_LAYER_CODE(mgmt_request)
NET_MGMT_GET_COMMAND(mgmt_request)
NET_MGMT_LAYER_L1
NET_MGMT_LAYER_L2
NET_MGMT_LAYER_L3
net_mgmt(_mgmt_request, _iface, _data, _len)
NET_MGMT_DEFINE_REQUEST_HANDLER(_mgmt_request)
NET_MGMT_REGISTER_REQUEST_HANDLER(_mgmt_request, _func)
net_mgmt_init_event_callback(...)
net_mgmt_add_event_callback(...)
net_mgmt_event_notify(...)
net_mgmt_event_init(...)
net_mgmt_event_notify_with_info(...)

Typedefs

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.
  • u32_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.

Enums

enum net_event_if_cmd

Values:

NET_EVENT_IF_CMD_DOWN = 1
NET_EVENT_IF_CMD_UP
enum net_event_ipv6_cmd

Values:

NET_EVENT_IPV6_CMD_ADDR_ADD = 1
NET_EVENT_IPV6_CMD_ADDR_DEL
NET_EVENT_IPV6_CMD_MADDR_ADD
NET_EVENT_IPV6_CMD_MADDR_DEL
NET_EVENT_IPV6_CMD_PREFIX_ADD
NET_EVENT_IPV6_CMD_PREFIX_DEL
NET_EVENT_IPV6_CMD_MCAST_JOIN
NET_EVENT_IPV6_CMD_MCAST_LEAVE
NET_EVENT_IPV6_CMD_ROUTER_ADD
NET_EVENT_IPV6_CMD_ROUTER_DEL
NET_EVENT_IPV6_CMD_ROUTE_ADD
NET_EVENT_IPV6_CMD_ROUTE_DEL
NET_EVENT_IPV6_CMD_DAD_SUCCEED
NET_EVENT_IPV6_CMD_DAD_FAILED
NET_EVENT_IPV6_CMD_NBR_ADD
NET_EVENT_IPV6_CMD_NBR_DEL
enum net_event_ipv4_cmd

Values:

NET_EVENT_IPV4_CMD_ADDR_ADD = 1
NET_EVENT_IPV4_CMD_ADDR_DEL
NET_EVENT_IPV4_CMD_ROUTER_ADD

Functions

static int net_mgmt_event_wait(u32_t mgmt_event_mask, u32_t *raised_event, struct net_if **iface, const void **info, int timeout)
static int net_mgmt_event_wait_on_iface(struct net_if *iface, u32_t mgmt_event_mask, u32_t *raised_event, const void **info, int timeout)
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.

Network layer 2 management

group net_l2

Network Layer 2 abstraction layer.

Defines

NET_L2_GET_NAME(_name)
NET_L2_DECLARE_PUBLIC(_name)
NET_L2_GET_CTX_TYPE(_name)
NET_L2_INIT(_name, _recv_fn, _send_fn, _reserve_fn, _enable_fn, _get_flags_fn)
NET_L2_GET_DATA(name, sfx)
NET_L2_DATA_INIT(name, sfx, ctx_type)

Enums

enum net_l2_flags

Values:

NET_L2_MULTICAST = BIT(0)

IP multicast supported

NET_L2_MULTICAST_SKIP_JOIN_SOLICIT_NODE = BIT(1)

Do not joint solicited node multicast group

NET_L2_PROMISC_MODE = BIT(2)

Is promiscuous mode supported

Application network context

group net_context

Application network context.

Defines

NET_CONTEXT_IN_USE

Is this context used or not

NET_CONTEXT_FAMILY

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

Type of the connection (datagram / stream)

NET_CONTEXT_PROTO

IP protocol (like UDP or TCP)

NET_CONTEXT_REMOTE_ADDR_SET

Remote address set

NET_CONTEXT_STATE_SHIFT
NET_CONTEXT_STATE_MASK
net_context_setup_pools(context, tx_pool, data_pool)

Set custom network buffer pools for context send operations.

Set custom network buffer pools used by the IP stack to allocate network buffers used by the context when sending data to the network. Using dedicated buffers may help make send operations on a given context more reliable, e.g. not be subject to buffer starvation due to operations on other network contexts. Buffer pools are set per context, but several contexts may share the same buffers. Note that there’s no support for per-context custom receive packet pools.

Parameters
  • context: Context that will use the given net_buf pools.
  • tx_pool: Pointer to the function that will return TX pool to the caller. The TX pool is used when sending data to network. There is one TX net_pkt for each network packet that is sent.
  • data_pool: Pointer to the function that will return DATA pool to the caller. The DATA pool is used to store data that is sent to the network.

Typedefs

typedef net_context_recv_cb_t

Network data receive callback.

The recv callback is called after a network data packet is received. This callback is called by RX thread so its stack and execution context is used here. Keep processing in the callback minimal to reduce the time spent blocked while handling packets.

Parameters
  • context: The context to use.
  • pkt: Network buffer that is received. If the pkt is not NULL, then the callback will own the buffer and it needs to to unref the pkt as soon as it has finished working with it. On EOF, pkt 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 pkt 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 packet is sent. This callback is called by TX thread so its stack and execution context is used here. Keep processing in the callback minimal to reduce the time spent blocked while handling packets.

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 was established or if there was an error while we were waiting for a connection attempt. This callback is called by RX thread so its stack and execution context is used here. Keep processing in the callback minimal to reduce the time spent blocked while handling packets.

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. For TCP connections, this callback is called by RX thread so its stack and execution context is used here. The callback is called after the TCP connection was established or if the connection failed. Keep processing in the callback minimal to reduce the time spent blocked while handling packets. For UDP connections, this callback is called immediately by net_context_connect() function. UDP is a connectionless protocol so the connection can be thought of being established immediately.

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_pkt_get_slab_func_t

Function that is called to get the slab that is used for net_pkt allocations.

Return
Pointer to valid struct k_mem_slab instance.

typedef net_pkt_get_pool_func_t

Function that is called to get the pool that is used for net_buf allocations.

Return
Pointer to valid struct net_buf_pool instance.

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

Enums

enum 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
enum net_context_option

Values:

NET_OPT_PRIORITY = 1

Functions

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

static struct net_pkt *net_context_create_ipv4(struct net_context *context, struct net_pkt *pkt, const struct in_addr *src, const struct in_addr *dst)

Create IPv4 packet in provided net_pkt from context.

Return
Return network packet that contains the IPv4 packet.
Parameters
  • context: Network context for a connection
  • pkt: Network packet
  • src: Source address, or NULL to choose a default
  • dst: Destination IPv4 address

static struct net_pkt *net_context_create_ipv6(struct net_context *context, struct net_pkt *pkt, const struct in6_addr *src, const struct in6_addr *dst)

Create IPv6 packet in provided net_pkt from context.

Return
Return network packet that contains the IPv6 packet.
Parameters
  • context: Network context for a connection
  • pkt: Network packet
  • src: Source address, or NULL to choose a default from context
  • dst: Destination IPv6 address

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, s32_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, s32_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_pkt *pkt, net_context_send_cb_t cb, s32_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
  • pkt: 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_pkt *pkt, const struct sockaddr *dst_addr, socklen_t addrlen, net_context_send_cb_t cb, s32_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
  • pkt: 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, s32_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 behavior 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 update 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.

int net_context_update_recv_wnd(struct net_context *context, s32_t delta)

Update TCP receive window for context.

This function should be used by an application which doesn’t fully process incoming data in its receive callback, but for example, queues it. In this case, receive callback should decrease the window (call this function with a negative value) by the size of queued data, and function(s) which dequeue data - with positive value corresponding to the dequeued size. For example, if receive callback gets a packet with the data size of 256 and queues it, it should call this function with delta of -256. If a function extracts 10 bytes of the queued data, it should call it with delta of 10.

Return
0 if ok, < 0 if error
Parameters
  • context: The TCP network context to use.
  • delta: Size, in bytes, by which to increase TCP receive window (negative value to decrease).

int net_context_set_option(struct net_context *context, enum net_context_option option, const void *value, size_t len)

Set an connection option for this context.

Return
0 if ok, <0 if error
Parameters
  • context: The network context to use.
  • option: Option to set
  • value: Option value
  • len: Option length

int net_context_get_option(struct net_context *context, enum net_context_option option, void *value, size_t *len)

Get connection option value for this context.

Return
0 if ok, <0 if error
Parameters
  • context: The network context to use.
  • option: Option to set
  • value: Option value
  • len: Option length (returned to caller)

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.

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.

struct

Option values

BSD Sockets compatible API

group bsd_sockets

BSD Sockets compatible API.

Defines

ZSOCK_POLLIN
ZSOCK_POLLOUT
ZSOCK_POLLERR
ZSOCK_MSG_PEEK
ZSOCK_MSG_DONTWAIT
SOL_TLS
TLS_SEC_TAG_LIST
TLS_HOSTNAME
TLS_CIPHERSUITE_LIST
TLS_CIPHERSUITE_USED
TLS_PEER_VERIFY
TLS_DTLS_ROLE

Functions

int zsock_socket(int family, int type, int proto)
int zsock_close(int sock)
int zsock_bind(int sock, const struct sockaddr *addr, socklen_t addrlen)
int zsock_connect(int sock, const struct sockaddr *addr, socklen_t addrlen)
int zsock_listen(int sock, int backlog)
int zsock_accept(int sock, struct sockaddr *addr, socklen_t *addrlen)
ssize_t zsock_sendto(int sock, const void *buf, size_t len, int flags, const struct sockaddr *dest_addr, socklen_t addrlen)
static ssize_t zsock_send(int sock, const void *buf, size_t len, int flags)
ssize_t zsock_recvfrom(int sock, void *buf, size_t max_len, int flags, struct sockaddr *src_addr, socklen_t *addrlen)
static ssize_t zsock_recv(int sock, void *buf, size_t max_len, int flags)
int zsock_fcntl(int sock, int cmd, int flags)
int zsock_poll(struct zsock_pollfd *fds, int nfds, int timeout)
int zsock_getsockopt(int sock, int level, int optname, void *optval, socklen_t *optlen)
int zsock_setsockopt(int sock, int level, int optname, const void *optval, socklen_t optlen)
int zsock_inet_pton(sa_family_t family, const char *src, void *dst)
int z_zsock_getaddrinfo_internal(const char *host, const char *service, const struct zsock_addrinfo *hints, struct zsock_addrinfo *res)
int zsock_getaddrinfo(const char *host, const char *service, const struct zsock_addrinfo *hints, struct zsock_addrinfo **res)

Network offloading support

group net_offload

Network offloading interface.

Network statistics

group net_stats

Network statistics library.

Typedefs

typedef u32_t net_stats_t
struct

Traffic class sent statistics

struct

Traffic class receive statistics

Trickle timer support

group trickle

Trickle algorithm library.

Defines

NET_TRICKLE_INFINITE_REDUNDANCY

Typedefs

typedef void (*net_trickle_cb_t)(struct net_trickle *trickle, bool do_suppress, void *user_data)

Functions

int net_trickle_create(struct net_trickle *trickle, u32_t Imin, u8_t Imax, u8_t k)

Create a Trickle timer.

Return
Return 0 if ok and <0 if error.
Parameters
  • trickle: Pointer to Trickle struct.
  • Imin: Imin configuration parameter in ms.
  • Imax: Max number of doublings.
  • k: Redundancy constant parameter. See RFC 6206 for details.

int net_trickle_start(struct net_trickle *trickle, net_trickle_cb_t cb, void *user_data)

Start a Trickle timer.

Return
Return 0 if ok and <0 if error.
Parameters
  • trickle: Pointer to Trickle struct.
  • cb: User callback to call at time T within the current trickle interval
  • user_data: User pointer that is passed to callback.

int net_trickle_stop(struct net_trickle *trickle)

Stop a Trickle timer.

Return
Return 0 if ok and <0 if error.
Parameters
  • trickle: Pointer to Trickle struct.

void net_trickle_consistency(struct net_trickle *trickle)

To be called by the protocol handler when it hears a consistent network transmission.

Parameters
  • trickle: Pointer to Trickle struct.

void net_trickle_inconsistency(struct net_trickle *trickle)

To be called by the protocol handler when it hears an inconsistent network transmission.

Parameters
  • trickle: Pointer to Trickle struct.

static bool net_trickle_is_running(struct net_trickle *trickle)

Check if the Trickle timer is running or not.

Return
Return True if timer is running and False if not.
Parameters
  • trickle: Pointer to Trickle struct.

UDP

group udp

UDP library.

Functions

static struct net_udp_hdr *net_udp_get_hdr(struct net_pkt *pkt, struct net_udp_hdr *hdr)
static struct net_udp_hdr *net_udp_set_hdr(struct net_pkt *pkt, struct net_udp_hdr *hdr)

Hostname Configuration Library

group net_hostname

Network hostname configuration library.

Functions

static const char *net_hostname_get(void)
static void net_hostname_init(void)
static int net_hostname_set_postfix(const u8_t *hostname_postfix, int postfix_len)

generic Precision Time Protocol (gPTP)

group gptp

generic Precision Time Protocol (gPTP) support

Defines

GPTP_CLOCK_ACCURACY_UNKNOWN
GPTP_OFFSET_SCALED_LOG_VAR_UNKNOWN
GPTP_PRIORITY1_NON_GM_CAPABLE
GPTP_PRIORITY2_DEFAULT
GPTP_POW2(exp)
GPTP_SYNC_MESSAGE
GPTP_DELAY_REQ_MESSAGE
GPTP_PATH_DELAY_REQ_MESSAGE
GPTP_PATH_DELAY_RESP_MESSAGE
GPTP_FOLLOWUP_MESSAGE
GPTP_DELAY_RESP_MESSAGE
GPTP_PATH_DELAY_FOLLOWUP_MESSAGE
GPTP_ANNOUNCE_MESSAGE
GPTP_SIGNALING_MESSAGE
GPTP_MANAGEMENT_MESSAGE
GPTP_IS_EVENT_MSG(msg_type)
GPTP_CLOCK_ID_LEN
GPTP_GET_CURRENT_TIME_USCALED_NS(port, uscaled_ns_ptr)

Typedefs

typedef gptp_phase_dis_callback_t

Define callback that is called after a phase discontinuity has been sent by the grandmaster.

Parameters
  • u8_t *gm_identity: A pointer to first element of a ClockIdentity array. The size of the array is GPTP_CLOCK_ID_LEN.
  • u16_t *gm_time_base: A pointer to the value of timeBaseIndicator of the current grandmaster.
  • struct scaled_ns *last_gm_ph_change: A pointer to the value of lastGmPhaseChange received from grandmaster.
  • double *last_gm_freq_change: A pointer to the value of lastGmFreqChange received from the grandmaster.

typedef gptp_port_cb_t

Callback used while iterating over gPTP ports.

Parameters
  • port: Port number
  • iface: Pointer to network interface
  • user_data: A valid pointer to user data or NULL

Functions

void gptp_register_phase_dis_cb(struct gptp_phase_dis_cb *phase_dis, gptp_phase_dis_callback_t cb)

Register a phase discontinuity callback.

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

void gptp_unregister_phase_dis_cb(struct gptp_phase_dis_cb *phase_dis)

Unregister a phase discontinuity callback.

Parameters
  • phase_dis: Caller specified handler for the callback.

void gptp_call_phase_dis_cb(void)

Call a phase discontinuity callback function.

int gptp_event_capture(struct net_ptp_time *slave_time, bool *gm_present)

Get gPTP time.

Return
Error code. 0 if no error.
Parameters
  • slave_time: A pointer to structure where timestamp will be saved.
  • gm_present: A pointer to a boolean where status of the presence of a grand master will be saved.

char *gptp_sprint_clock_id(const u8_t *clk_id, char *output, size_t output_len)

Utility function to print clock id to a user supplied buffer.

Return
Pointer to output buffer
Parameters
  • clk_id: Clock id
  • output: Output buffer
  • output_len: Output buffer len

void gptp_foreach_port(gptp_port_cb_t cb, void *user_data)

Go through all the gPTP ports and call callback for each of them.

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

struct gptp_domain *gptp_get_domain(void)

Get gPTP domain.

This contains all the configuration / status of the gPTP domain.

Return
Pointer to domain or NULL if not found.

struct gptp_scaled_ns
#include <gptp.h>

Scaled Nanoseconds.

struct gptp_uscaled_ns
#include <gptp.h>

UScaled Nanoseconds.

struct gptp_port_identity
#include <gptp.h>

Port Identity.

struct gptp_phase_dis_cb
#include <gptp.h>

Phase discontinuity callback structure.

Stores the phase discontinuity 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 technologies

Ethernet

group ethernet

Ethernet support functions.

Defines

NET_ETH_HDR(pkt)
NET_ETH_PTYPE_ARP
NET_ETH_PTYPE_IP
NET_ETH_PTYPE_IPV6
NET_ETH_PTYPE_VLAN
NET_ETH_PTYPE_PTP
NET_ETH_PTYPE_LLDP
NET_ETH_MINIMAL_FRAME_SIZE
NET_VLAN_MAX_COUNT
ETHERNET_L2_CTX_TYPE
ETH_NET_DEVICE_INIT(dev_name, drv_name, init_fn, data, cfg_info, prio, api, mtu)
MII_BMCR
MII_BMSR
MII_PHYID1R
MII_PHYID2R
MII_ANAR
MII_ANLPAR
MII_ANER
MII_ANNPTR
MII_ANLPRNPR
MII_MMD_ACR
MII_MMD_AADR
MII_ESTAT
MII_BMCR_RESET
MII_BMCR_LOOPBACK
MII_BMCR_SPEED_LSB
MII_BMCR_AUTONEG_ENABLE
MII_BMCR_POWER_DOWN
MII_BMCR_ISOLATE
MII_BMCR_AUTONEG_RESTART
MII_BMCR_DUPLEX_MODE
MII_BMCR_SPEED_MSB
MII_BMCR_SPEED_MASK
MII_BMCR_SPEED_10
MII_BMCR_SPEED_100
MII_BMCR_SPEED_1000
MII_BMSR_100BASE_T4
MII_BMSR_100BASE_X_FULL
MII_BMSR_100BASE_X_HALF
MII_BMSR_10_FULL
MII_BMSR_10_HALF
MII_BMSR_100BASE_T2_FULL
MII_BMSR_100BASE_T2_HALF
MII_BMSR_EXTEND_STATUS
MII_BMSR_MF_PREAMB_SUPPR
MII_BMSR_AUTONEG_COMPLETE
MII_BMSR_REMOTE_FAULT
MII_BMSR_AUTONEG_ABILITY
MII_BMSR_JABBER_DETECT
MII_BMSR_EXTEND_CAPAB
MII_ADVERTISE_NEXT_PAGE
MII_ADVERTISE_LPACK
MII_ADVERTISE_REMOTE_FAULT
MII_ADVERTISE_ASYM_PAUSE
MII_ADVERTISE_PAUSE
MII_ADVERTISE_100BASE_T4
MII_ADVERTISE_100_FULL
MII_ADVERTISE_100_HALF
MII_ADVERTISE_10_FULL
MII_ADVERTISE_10_HALF
MII_ADVERTISE_SEL_MASK
MII_ADVERTISE_SEL_IEEE_802_3
MII_ADVERTISE_ALL

Enums

enum ethernet_hw_caps

Values:

ETHERNET_HW_TX_CHKSUM_OFFLOAD = BIT(0)

TX Checksum offloading supported

ETHERNET_HW_RX_CHKSUM_OFFLOAD = BIT(1)

RX Checksum offloading supported

ETHERNET_HW_VLAN = BIT(2)

VLAN supported

ETHERNET_AUTO_NEGOTIATION_SET = BIT(3)

Enabling/disabling auto negotiation supported

10 Mbits link supported

100 Mbits link supported

1 Gbits link supported

ETHERNET_DUPLEX_SET = BIT(7)

Changing duplex (half/full) supported

ETHERNET_PTP = BIT(8)

IEEE 802.1AS (gPTP) clock supported

ETHERNET_QAV = BIT(9)

IEEE 802.1Qav (credit-based shaping) supported

ETHERNET_PROMISC_MODE = BIT(10)

Promiscuous mode supported

ETHERNET_PRIORITY_QUEUES = BIT(11)

Priority queues available

ETHERNET_HW_FILTERING = BIT(12)

MAC address filtering supported

ETHERNET_LLDP = BIT(13)

Link Layer Discovery Protocol supported

enum ethernet_config_type

Values:

ETHERNET_CONFIG_TYPE_AUTO_NEG
ETHERNET_CONFIG_TYPE_LINK
ETHERNET_CONFIG_TYPE_DUPLEX
ETHERNET_CONFIG_TYPE_MAC_ADDRESS
ETHERNET_CONFIG_TYPE_QAV_PARAM
ETHERNET_CONFIG_TYPE_PROMISC_MODE
ETHERNET_CONFIG_TYPE_PRIORITY_QUEUES_NUM
ETHERNET_CONFIG_TYPE_FILTER
enum ethernet_qav_param_type

Values:

ETHERNET_QAV_PARAM_TYPE_DELTA_BANDWIDTH
ETHERNET_QAV_PARAM_TYPE_IDLE_SLOPE
ETHERNET_QAV_PARAM_TYPE_OPER_IDLE_SLOPE
ETHERNET_QAV_PARAM_TYPE_TRAFFIC_CLASS
ETHERNET_QAV_PARAM_TYPE_STATUS
enum ethernet_filter_type

Values:

ETHERNET_FILTER_TYPE_SRC_MAC_ADDRESS
ETHERNET_FILTER_TYPE_DST_MAC_ADDRESS

Functions

void ethernet_init(struct net_if *iface)

Initialize Ethernet L2 stack for a given interface.

Parameters
  • iface: A valid pointer to a network interface

static bool net_eth_is_addr_broadcast(struct net_eth_addr *addr)
static bool net_eth_is_addr_multicast(struct net_eth_addr *addr)
static bool net_eth_is_addr_lldp_multicast(struct net_eth_addr *addr)
const struct net_eth_addr *net_eth_broadcast_addr(void)
void net_eth_ipv6_mcast_to_mac_addr(const struct in6_addr *ipv6_addr, struct net_eth_addr *mac_addr)

Convert IPv6 multicast address to Ethernet address.

Parameters
  • ipv6_addr: IPv6 multicast address
  • mac_addr: Output buffer for Ethernet address

static enum ethernet_hw_caps net_eth_get_hw_capabilities(struct net_if *iface)

Return ethernet device hardware capability information.

Return
Hardware capabilities
Parameters
  • iface: Network interface

static int net_eth_vlan_enable(struct net_if *iface, u16_t vlan_tag)
static int net_eth_vlan_disable(struct net_if *iface, u16_t vlan_tag)
static u16_t net_eth_get_vlan_tag(struct net_if *iface)
static struct net_if *net_eth_get_vlan_iface(struct net_if *iface, u16_t tag)
static bool net_eth_get_vlan_status(struct net_if *iface)
struct net_eth_hdr *net_eth_fill_header(struct ethernet_context *ctx, struct net_pkt *pkt, u32_t ptype, u8_t *src, u8_t *dst)

Fill ethernet header in network packet.

Return
Pointer to ethernet header struct inside net_buf.
Parameters
  • ctx: Ethernet context
  • pkt: Network packet
  • ptype: Upper level protocol type (in network byte order)
  • src: Source ethernet address
  • dst: Destination ethernet address

void net_eth_carrier_on(struct net_if *iface)

Inform ethernet L2 driver that ethernet carrier is detected. This happens when cable is connected.

Parameters
  • iface: Network interface

void net_eth_carrier_off(struct net_if *iface)

Inform ethernet L2 driver that ethernet carrier was lost. This happens when cable is disconnected.

Parameters
  • iface: Network interface

int net_eth_promisc_mode(struct net_if *iface, bool enable)

Set promiscuous mode either ON or OFF.

Return
0 if mode set or unset was successful, <0 otherwise.
Parameters
  • iface: Network interface
  • enable: on (true) or off (false)

struct device *net_eth_get_ptp_clock(struct net_if *iface)

Return PTP clock that is tied to this ethernet network interface.

Return
Pointer to PTP clock if found, NULL if not found or if this ethernet interface does not support PTP.
Parameters
  • iface: Network interface

static int net_eth_get_ptp_port(struct net_if *iface)
static int net_eth_set_lldpdu(struct net_if *iface, const struct net_lldpdu *lldpdu)

Set LLDP protocol data unit (LLDPDU) for the network interface.

Return
<0 if error, index in lldp array if iface is found there
Parameters
  • iface: Network interface
  • lldpdu: LLDPDU pointer

static void net_eth_unset_lldpdu(struct net_if *iface)

Unset LLDP protocol data unit (LLDPDU) for the network interface.

Parameters
  • iface: Network interface

struct ethernet_context
#include <ethernet.h>

Ethernet L2 context that is needed for VLAN

Ethernet Management

group ethernet_mgmt

Ethernet library.

Defines

NET_REQUEST_ETHERNET_SET_AUTO_NEGOTIATION
NET_REQUEST_ETHERNET_SET_DUPLEX
NET_REQUEST_ETHERNET_SET_MAC_ADDRESS
NET_REQUEST_ETHERNET_SET_QAV_PARAM
NET_REQUEST_ETHERNET_SET_PROMISC_MODE
NET_REQUEST_ETHERNET_GET_PRIORITY_QUEUES_NUM
NET_REQUEST_ETHERNET_GET_QAV_PARAM
NET_EVENT_ETHERNET_CARRIER_ON
NET_EVENT_ETHERNET_CARRIER_OFF
NET_EVENT_ETHERNET_VLAN_TAG_ENABLED
NET_EVENT_ETHERNET_VLAN_TAG_DISABLED

Enums

enum net_request_ethernet_cmd

Values:

NET_REQUEST_ETHERNET_CMD_SET_AUTO_NEGOTIATION = 1
NET_REQUEST_ETHERNET_CMD_SET_LINK
NET_REQUEST_ETHERNET_CMD_SET_DUPLEX
NET_REQUEST_ETHERNET_CMD_SET_MAC_ADDRESS
NET_REQUEST_ETHERNET_CMD_SET_QAV_PARAM
NET_REQUEST_ETHERNET_CMD_SET_PROMISC_MODE
NET_REQUEST_ETHERNET_CMD_GET_PRIORITY_QUEUES_NUM
NET_REQUEST_ETHERNET_CMD_GET_QAV_PARAM
enum net_event_ethernet_cmd

Values:

NET_EVENT_ETHERNET_CMD_CARRIER_ON = 1
NET_EVENT_ETHERNET_CMD_CARRIER_OFF
NET_EVENT_ETHERNET_CMD_VLAN_TAG_ENABLED
NET_EVENT_ETHERNET_CMD_VLAN_TAG_DISABLED

Functions

static void ethernet_mgmt_raise_carrier_on_event(struct net_if *iface)
static void ethernet_mgmt_raise_carrier_off_event(struct net_if *iface)
static void ethernet_mgmt_raise_vlan_enabled_event(struct net_if *iface, u16_t tag)
static void ethernet_mgmt_raise_vlan_disabled_event(struct net_if *iface, u16_t tag)

Virtual LAN definitions and helpers

group vlan

VLAN definitions and helpers.

Defines

NET_VLAN_TAG_UNSPEC

Functions

static u16_t net_eth_vlan_get_vid(u16_t tci)
static u8_t net_eth_vlan_get_dei(u16_t tci)
static u8_t net_eth_vlan_get_pcp(u16_t tci)
static u16_t net_eth_vlan_set_vid(u16_t tci, u16_t vid)
static u16_t net_eth_vlan_set_dei(u16_t tci, bool dei)
static u16_t net_eth_vlan_set_pcp(u16_t tci, u8_t pcp)

IEEE 802.15.4

group ieee802154

IEEE 802.15.4 library.

Defines

IEEE802154_MAX_ADDR_LENGTH
IEEE802154_NO_CHANNEL
IEEE802154_L2_CTX_TYPE
IEEE802154_AR_FLAG_SET

Enums

enum ieee802154_hw_caps

Values:

IEEE802154_HW_FCS = BIT(0)
IEEE802154_HW_PROMISC = BIT(1)
IEEE802154_HW_FILTER = BIT(2)
IEEE802154_HW_CSMA = BIT(3)
IEEE802154_HW_2_4_GHZ = BIT(4)
IEEE802154_HW_TX_RX_ACK = BIT(5)
IEEE802154_HW_SUB_GHZ = BIT(6)
enum ieee802154_filter_type

Values:

IEEE802154_FILTER_TYPE_IEEE_ADDR
IEEE802154_FILTER_TYPE_SHORT_ADDR
IEEE802154_FILTER_TYPE_PAN_ID
IEEE802154_FILTER_TYPE_SRC_IEEE_ADDR
IEEE802154_FILTER_TYPE_SRC_SHORT_ADDR

Functions

static bool ieee802154_is_ar_flag_set(struct net_pkt *pkt)

Check if AR flag is set on the frame inside given net_pkt.

Return
True if AR flag is set, False otherwise
Parameters
  • pkt: A valid pointer on a net_pkt structure, must not be NULL, and its length should be at least made of 1 byte (ACK frames are the smallest frames on 15.4 and made of 3 bytes, not not counting the FCS part).

int ieee802154_radio_send(struct net_if *iface, struct net_pkt *pkt)

Radio driver sending function that hw drivers should use.

This function should be used to fill in struct net_if’s send pointer.

Return
0 on success, negative value otherwise
Parameters
  • iface: A valid pointer on a network interface to send from
  • pkt: A valid pointer on a packet to send

enum net_verdict ieee802154_radio_handle_ack(struct net_if *iface, struct net_pkt *pkt)

Radio driver ACK handling function that hw drivers should use.

ACK handling requires fast handling and thus such function helps to hook directly the hw drivers to the radio driver.

Return
NET_OK if it was handled, NET_CONTINUE otherwise
Parameters
  • iface: A valid pointer on a network interface that received the packet
  • pkt: A valid pointer on a packet to check

void ieee802154_init(struct net_if *iface)

Initialize L2 stack for a given interface.

Parameters
  • iface: A valid pointer on a network interface

IEEE 802.15.4 Management

group ieee802154_mgmt

IEEE 802.15.4 library.

Defines

IEEE802154_MAX_ADDR_LENGTH
NET_REQUEST_IEEE802154_SET_ACK
NET_REQUEST_IEEE802154_UNSET_ACK
NET_REQUEST_IEEE802154_PASSIVE_SCAN
NET_REQUEST_IEEE802154_ACTIVE_SCAN
NET_REQUEST_IEEE802154_CANCEL_SCAN
NET_REQUEST_IEEE802154_ASSOCIATE
NET_REQUEST_IEEE802154_DISASSOCIATE
NET_REQUEST_IEEE802154_SET_CHANNEL
NET_REQUEST_IEEE802154_GET_CHANNEL
NET_REQUEST_IEEE802154_SET_PAN_ID
NET_REQUEST_IEEE802154_GET_PAN_ID
NET_REQUEST_IEEE802154_SET_EXT_ADDR
NET_REQUEST_IEEE802154_GET_EXT_ADDR
NET_REQUEST_IEEE802154_SET_SHORT_ADDR
NET_REQUEST_IEEE802154_GET_SHORT_ADDR
NET_REQUEST_IEEE802154_GET_TX_POWER
NET_REQUEST_IEEE802154_SET_TX_POWER
NET_EVENT_IEEE802154_SCAN_RESULT
IEEE802154_IS_CHAN_SCANNED(_channel_set, _chan)
IEEE802154_IS_CHAN_UNSCANNED(_channel_set, _chan)
IEEE802154_ALL_CHANNELS

Enums

enum net_request_ieee802154_cmd

Values:

NET_REQUEST_IEEE802154_CMD_SET_ACK = 1
NET_REQUEST_IEEE802154_CMD_UNSET_ACK
NET_REQUEST_IEEE802154_CMD_PASSIVE_SCAN
NET_REQUEST_IEEE802154_CMD_ACTIVE_SCAN
NET_REQUEST_IEEE802154_CMD_CANCEL_SCAN
NET_REQUEST_IEEE802154_CMD_ASSOCIATE
NET_REQUEST_IEEE802154_CMD_DISASSOCIATE
NET_REQUEST_IEEE802154_CMD_SET_CHANNEL
NET_REQUEST_IEEE802154_CMD_GET_CHANNEL
NET_REQUEST_IEEE802154_CMD_SET_PAN_ID
NET_REQUEST_IEEE802154_CMD_GET_PAN_ID
NET_REQUEST_IEEE802154_CMD_SET_EXT_ADDR
NET_REQUEST_IEEE802154_CMD_GET_EXT_ADDR
NET_REQUEST_IEEE802154_CMD_SET_SHORT_ADDR
NET_REQUEST_IEEE802154_CMD_GET_SHORT_ADDR
NET_REQUEST_IEEE802154_CMD_GET_TX_POWER
NET_REQUEST_IEEE802154_CMD_SET_TX_POWER
NET_REQUEST_IEEE802154_CMD_SET_SECURITY_SETTINGS
NET_REQUEST_IEEE802154_CMD_GET_SECURITY_SETTINGS
enum net_event_ieee802154_cmd

Values:

NET_EVENT_IEEE802154_CMD_SCAN_RESULT = 1
struct ieee802154_req_params
#include <ieee802154_mgmt.h>

Scanning parameters.

Used to request a scan and get results as well

struct ieee802154_security_params
#include <ieee802154_mgmt.h>

Security parameters.

Used to setup the link-layer security settings

Network and application libraries

Network application

group net_app

Network application library.

Defines

net_app_set_net_pkt_pool(...)

Typedefs

typedef net_app_recv_cb_t

Network data receive callback.

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

Parameters
  • ctx: The context to use.
  • pkt: Network buffer that is received. If the pkt is not NULL, then the callback will own the buffer and it needs to to unref the pkt as soon as it has finished working with it. On EOF, pkt 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 pkt parameter is set to NULL.
  • user_data: The user data given in init call.

typedef net_app_connect_cb_t

Connection callback.

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

Parameters
  • ctx: 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 init call.

typedef net_app_send_cb_t

Network data send callback.

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

Parameters
  • ctx: 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.
  • user_data_send: The user data given in net_app_send() call.
  • user_data: The user data given in init call.

typedef net_app_close_cb_t

Close callback.

The close callback is called after a connection is being shutdown.

Parameters
  • ctx: The context to use.
  • status: Error code for the closing.
  • user_data: The user data given in init call.

typedef int (*net_app_send_data_t)(struct net_pkt *pkt, const struct sockaddr *dst_addr, socklen_t addrlen, net_context_send_cb_t cb, s32_t timeout, void *token, void *user_data)

Enums

enum net_app_type

Values:

NET_APP_UNSPEC = 0
NET_APP_SERVER
NET_APP_CLIENT

Functions

int net_app_set_cb(struct net_app_ctx *ctx, net_app_connect_cb_t connect_cb, net_app_recv_cb_t recv_cb, net_app_send_cb_t send_cb, net_app_close_cb_t close_cb)

Set various network application callbacks.

Return
0 if ok, <0 if error.
Parameters
  • ctx: Network app context.
  • connect_cb: Connect callback.
  • recv_cb: Data receive callback.
  • send_cb: Data sent callback.
  • close_cb: Close callback.

int net_app_send_pkt(struct net_app_ctx *ctx, struct net_pkt *pkt, const struct sockaddr *dst, socklen_t dst_len, s32_t timeout, void *user_data_send)

Send data that is found in net_pkt to peer.

If the function return < 0, then it is caller responsibility to unref the pkt. If the packet was sent successfully, then the lower IP stack will release the network pkt.

Return
0 if ok, <0 if error.
Parameters
  • ctx: Network application context.
  • pkt: Network packet to send.
  • dst: Destination address where to send packet. This is ignored for TCP data.
  • dst_len: Destination address structure size
  • timeout: How long to wait the send before giving up.
  • user_data_send: User data specific to this send call.

int net_app_send_buf(struct net_app_ctx *ctx, u8_t *buf, size_t buf_len, const struct sockaddr *dst, socklen_t dst_len, s32_t timeout, void *user_data_send)

Send data that is found in user specified buffer to peer.

Return
0 if ok, <0 if error.
Parameters
  • ctx: Network application context.
  • buf: Buffer to send.
  • buf_len: Amount of data to send.
  • dst: Destination address where to send packet. This is ignored for TCP data.
  • dst_len: Destination address structure size
  • timeout: How long to wait the send before giving up.
  • user_data_send: User data specific to this send call.

struct net_pkt *net_app_get_net_pkt(struct net_app_ctx *ctx, sa_family_t family, s32_t timeout)

Create network packet.

Return
valid net_pkt if ok, NULL if error.
Parameters
  • ctx: Network application context.
  • family: What kind of network packet to get (AF_INET or AF_INET6)
  • timeout: How long to wait the send before giving up.

struct net_pkt *net_app_get_net_pkt_with_dst(struct net_app_ctx *ctx, const struct sockaddr *dst, s32_t timeout)

Create network packet based on dst address.

Return
valid net_pkt if ok, NULL if error.
Parameters
  • ctx: Network application context.
  • dst: Destination address to select net_context
  • timeout: How long to wait the send before giving up.

struct net_buf *net_app_get_net_buf(struct net_app_ctx *ctx, struct net_pkt *pkt, s32_t timeout)

Create network buffer that will hold network data.

The returned net_buf is automatically appended to the end of network packet fragment chain.

Return
valid net_pkt if ok, NULL if error.
Parameters
  • ctx: Network application context.
  • pkt: Network packet to where the data buf is appended.
  • timeout: How long to wait the send before giving up.

int net_app_close(struct net_app_ctx *ctx)

Close a network connection to peer.

Return
0 if ok, <0 if error.
Parameters
  • ctx: Network application context.

int net_app_close2(struct net_app_ctx *ctx, struct net_context *net_ctx)

Close a specific network connection.

Return
0 if ok, <0 if error.
Parameters
  • ctx: Network application context.
  • net_ctx: Network context.

int net_app_release(struct net_app_ctx *ctx)

Release this network application context.

No network data will be received via this context after this call.

Return
0 if ok, <0 if error.
Parameters
  • ctx: Network application context.

struct net_app_cb
#include <net_app.h>

Network application callbacks

struct net_app_ctx
#include <net_app.h>

Network application context.

DHCPv4

group dhcpv4

DHCPv4.

Enums

enum 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_DISABLED
NET_DHCPV4_INIT
NET_DHCPV4_SELECTING
NET_DHCPV4_REQUESTING
NET_DHCPV4_RENEWING
NET_DHCPV4_REBINDING
NET_DHCPV4_BOUND

Functions

void net_dhcpv4_start(struct net_if *iface)

Start DHCPv4 client on an iface.

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

void net_dhcpv4_stop(struct net_if *iface)

Stop DHCPv4 client on an iface.

Stop DHCPv4 client on a given interface. DHCPv4 client will remove all configuration obtained from a DHCP server from the interface and stop any further negotiation with the server.

Parameters
  • iface: A valid pointer on an interface

const char *net_dhcpv4_state_name(enum net_dhcpv4_state state)

DHCPv4 state name.

MQTT 3.1.1

group mqtt

MQTT library.

Enums

enum 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_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_protocol

MQTT protocol version.

Values:

MQTT_311 = 4
enum mqtt_qos

See MQTT 4.3 Quality of Service levels and protocol flows.

Values:

MQTT_QoS0 = 0
MQTT_QoS1
MQTT_QoS2

Functions

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
  • 0: always

int mqtt_close(struct mqtt_ctx *ctx)

Release the MQTT context structure

Parameters
  • ctx: MQTT context structure
Return Value
  • 0: on success, and <0 if error

int mqtt_connect(struct mqtt_ctx *ctx)

Connect to an MQTT broker

Parameters
  • ctx: MQTT context structure
Return Value
  • 0: on success, and <0 if error

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, u16_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, u16_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, u16_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, u16_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, u16_t pkt_id, u8_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, u16_t pkt_id, u8_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.

struct mqtt_publish_msg
#include <mqtt_types.h>

MQTT Publish Message.

CoAP

group coap

COAP library.

Defines

COAP_REQUEST_MASK
coap_make_response_code(clas, det)
COAP_CODE_EMPTY
COAP_WELL_KNOWN_CORE_PATH

This resource should be added before all other resources that should be included in the responses of the .well-known/core resource.

Typedefs

typedef coap_method_t

Type of the callback being called when a resource’s method is invoked by the remote entity.

typedef coap_notify_t

Type of the callback being called when a resource’s has observers to be informed when an update happens.

typedef coap_reply_t

Helper function to be called when a response matches the a pending request.

Enums

enum coap_option_num

Set of CoAP packet options we are aware of.

Users may add options other than these to their packets, provided they know how to format them correctly. The only restriction is that all options must be added to a packet in numeric order.

Refer to RFC 7252, section 12.2 for more information.

Values:

COAP_OPTION_IF_MATCH = 1
COAP_OPTION_URI_HOST = 3
COAP_OPTION_ETAG = 4
COAP_OPTION_IF_NONE_MATCH = 5
COAP_OPTION_OBSERVE = 6
COAP_OPTION_URI_PORT = 7
COAP_OPTION_LOCATION_PATH = 8
COAP_OPTION_URI_PATH = 11
COAP_OPTION_CONTENT_FORMAT = 12
COAP_OPTION_MAX_AGE = 14
COAP_OPTION_URI_QUERY = 15
COAP_OPTION_ACCEPT = 17
COAP_OPTION_LOCATION_QUERY = 20
COAP_OPTION_BLOCK2 = 23
COAP_OPTION_BLOCK1 = 27
COAP_OPTION_SIZE2 = 28
COAP_OPTION_PROXY_URI = 35
COAP_OPTION_PROXY_SCHEME = 39
COAP_OPTION_SIZE1 = 60
enum coap_method

Available request methods.

To be used when creating a request or a response.

Values:

COAP_METHOD_GET = 1
COAP_METHOD_POST = 2
COAP_METHOD_PUT = 3
COAP_METHOD_DELETE = 4
enum coap_msgtype

CoAP packets may be of one of these types.

Values:

COAP_TYPE_CON = 0

Confirmable message.

The packet is a request or response the destination end-point must acknowledge.

COAP_TYPE_NON_CON = 1

Non-confirmable message.

The packet is a request or response that doesn’t require acknowledgements.

COAP_TYPE_ACK = 2

Acknowledge.

Response to a confirmable message.

COAP_TYPE_RESET = 3

Reset.

Rejecting a packet for any reason is done by sending a message of this type.

enum coap_response_code

Set of response codes available for a response packet.

To be used when creating a response.

Values:

COAP_RESPONSE_CODE_OK = (( 2 << 5) | ( 0 ))
COAP_RESPONSE_CODE_CREATED = (( 2 << 5) | ( 1 ))
COAP_RESPONSE_CODE_DELETED = (( 2 << 5) | ( 2 ))
COAP_RESPONSE_CODE_VALID = (( 2 << 5) | ( 3 ))
COAP_RESPONSE_CODE_CHANGED = (( 2 << 5) | ( 4 ))
COAP_RESPONSE_CODE_CONTENT = (( 2 << 5) | ( 5 ))
COAP_RESPONSE_CODE_CONTINUE = (( 2 << 5) | ( 31 ))
COAP_RESPONSE_CODE_BAD_REQUEST = (( 4 << 5) | ( 0 ))
COAP_RESPONSE_CODE_UNAUTHORIZED = (( 4 << 5) | ( 1 ))
COAP_RESPONSE_CODE_BAD_OPTION = (( 4 << 5) | ( 2 ))
COAP_RESPONSE_CODE_FORBIDDEN = (( 4 << 5) | ( 3 ))
COAP_RESPONSE_CODE_NOT_FOUND = (( 4 << 5) | ( 4 ))
COAP_RESPONSE_CODE_NOT_ALLOWED = (( 4 << 5) | ( 5 ))
COAP_RESPONSE_CODE_NOT_ACCEPTABLE = (( 4 << 5) | ( 6 ))
COAP_RESPONSE_CODE_INCOMPLETE = (( 4 << 5) | ( 8 ))
COAP_RESPONSE_CODE_PRECONDITION_FAILED = (( 4 << 5) | ( 12 ))
COAP_RESPONSE_CODE_REQUEST_TOO_LARGE = (( 4 << 5) | ( 13 ))
COAP_RESPONSE_CODE_UNSUPPORTED_CONTENT_FORMAT

=

(( 4 << 5) | ( 15 ))


COAP_RESPONSE_CODE_INTERNAL_ERROR = (( 5 << 5) | ( 0 ))
COAP_RESPONSE_CODE_NOT_IMPLEMENTED = (( 5 << 5) | ( 1 ))
COAP_RESPONSE_CODE_BAD_GATEWAY = (( 5 << 5) | ( 2 ))
COAP_RESPONSE_CODE_SERVICE_UNAVAILABLE = (( 5 << 5) | ( 3 ))
COAP_RESPONSE_CODE_GATEWAY_TIMEOUT = (( 5 << 5) | ( 4 ))
COAP_RESPONSE_CODE_PROXYING_NOT_SUPPORTED

=

(( 5 << 5) | ( 5 ))


enum coap_block_size

Represents the size of each block that will be transferred using block-wise transfers [RFC7959]:

Each entry maps directly to the value that is used in the wire.

https://tools.ietf.org/html/rfc7959

Values:

COAP_BLOCK_16
COAP_BLOCK_32
COAP_BLOCK_64
COAP_BLOCK_128
COAP_BLOCK_256
COAP_BLOCK_512
COAP_BLOCK_1024

Functions

void coap_observer_init(struct coap_observer *observer, const struct coap_packet *request, const struct sockaddr *addr)

Indicates that the remote device referenced by addr, with request, wants to observe a resource.

Parameters
  • observer: Observer to be initialized
  • request: Request on which the observer will be based
  • addr: Address of the remote device

bool coap_register_observer(struct coap_resource *resource, struct coap_observer *observer)

After the observer is initialized, associate the observer with an resource.

Return
true if this is the first observer added to this resource.
Parameters
  • resource: Resource to add an observer
  • observer: Observer to be added

void coap_remove_observer(struct coap_resource *resource, struct coap_observer *observer)

Remove this observer from the list of registered observers of that resource.

Parameters
  • resource: Resource in which to remove the observer
  • observer: Observer to be removed

struct coap_observer *coap_find_observer_by_addr(struct coap_observer *observers, size_t len, const struct sockaddr *addr)

Returns the observer that matches address addr.

Return
A pointer to a observer if a match is found, NULL otherwise.
Parameters
  • observers: Pointer to the array of observers
  • len: Size of the array of observers
  • addr: Address of the endpoint observing a resource

struct coap_observer *coap_observer_next_unused(struct coap_observer *observers, size_t len)

Returns the next available observer representation.

Return
A pointer to a observer if there’s an available observer, NULL otherwise.
Parameters
  • observers: Pointer to the array of observers
  • len: Size of the array of observers

void coap_reply_init(struct coap_reply *reply, const struct coap_packet *request)

Indicates that a reply is expected for request.

Parameters
  • reply: Reply structure to be initialized
  • request: Request from which reply will be based

int coap_packet_parse(struct coap_packet *cpkt, struct net_pkt *pkt, struct coap_option *options, u8_t opt_num)

Parses the CoAP packet in pkt, validating it and initializing cpkt. pkt must remain valid while cpkt is used.

Return
0 in case of success or negative in case of error.
Parameters
  • cpkt: Packet to be initialized from received pkt.
  • pkt: Network Packet containing a CoAP packet, its data pointer is positioned on the start of the CoAP packet.
  • options: Parse options and cache its details.
  • opt_num: Number of options

int coap_packet_init(struct coap_packet *cpkt, struct net_pkt *pkt, u8_t ver, u8_t type, u8_t tokenlen, u8_t *token, u8_t code, u16_t id)

Creates a new CoAP packet from a net_pkt. pkt must remain valid while cpkt is used.

Return
0 in case of success or negative in case of error.
Parameters
  • cpkt: New packet to be initialized using the storage from pkt.
  • pkt: Network Packet that will contain a CoAP packet
  • ver: CoAP header version
  • type: CoAP header type
  • tokenlen: CoAP header token length
  • token: CoAP header token
  • code: CoAP header code
  • id: CoAP header message id

int coap_pending_init(struct coap_pending *pending, const struct coap_packet *request, const struct sockaddr *addr)

Initialize a pending request with a request.

The request’s fields are copied into the pending struct, so request doesn’t have to live for as long as the pending struct lives, but net_pkt needs to live for at least that long.

Return
0 in case of success or negative in case of error.
Parameters
  • pending: Structure representing the waiting for a confirmation message, initialized with data from request
  • request: Message waiting for confirmation
  • addr: Address to send the retransmission

struct coap_pending *coap_pending_next_unused(struct coap_pending *pendings, size_t len)

Returns the next available pending struct, that can be used to track the retransmission status of a request.

Return
pointer to a free coap_pending structure, NULL in case none could be found.
Parameters

struct coap_reply *coap_reply_next_unused(struct coap_reply *replies, size_t len)

Returns the next available reply struct, so it can be used to track replies and notifications received.

Return
pointer to a free coap_reply structure, NULL in case none could be found.
Parameters
  • replies: Pointer to the array of coap_reply structures
  • len: Size of the array of coap_reply structures

struct coap_pending *coap_pending_received(const struct coap_packet *response, struct coap_pending *pendings, size_t len)

After a response is received, clear all pending retransmissions related to that response.

Return
pointer to the associated coap_pending structure, NULL in case none could be found.
Parameters
  • response: The received response
  • pendings: Pointer to the array of coap_reply structures
  • len: Size of the array of coap_reply structures

struct coap_reply *coap_response_received(const struct coap_packet *response, const struct sockaddr *from, struct coap_reply *replies, size_t len)

After a response is received, call coap_reply_t handler registered in coap_reply structure.

Return
Pointer to the reply matching the packet received, NULL if none could be found.
Parameters
  • response: A response received
  • from: Address from which the response was received
  • replies: Pointer to the array of coap_reply structures
  • len: Size of the array of coap_reply structures

struct coap_pending *coap_pending_next_to_expire(struct coap_pending *pendings, size_t len)

Returns the next pending about to expire, pending->timeout informs how many ms to next expiration.

Return
The next coap_pending to expire, NULL if none is about to expire.
Parameters

bool coap_pending_cycle(struct coap_pending *pending)

After a request is sent, user may want to cycle the pending retransmission so the timeout is updated.

Return
false if this is the last retransmission.
Parameters
  • pending: Pending representation to have its timeout updated

void coap_pending_clear(struct coap_pending *pending)

Cancels the pending retransmission, so it again becomes available.

Parameters
  • pending: Pending representation to be canceled

void coap_reply_clear(struct coap_reply *reply)

Cancels awaiting for this reply, so it becomes available again.

Parameters
  • reply: The reply to be canceled

int coap_handle_request(struct coap_packet *cpkt, struct coap_resource *resources, struct coap_option *options, u8_t opt_num)

When a request is received, call the appropriate methods of the matching resources.

Return
0 in case of success or negative in case of error.
Parameters
  • cpkt: Packet received
  • resources: Array of known resources
  • options: Parsed options from coap_packet_parse()
  • opt_num: Number of options

int coap_resource_notify(struct coap_resource *resource)

Indicates that this resource was updated and that the notify callback should be called for every registered observer.

Return
0 in case of success or negative in case of error.
Parameters
  • resource: Resource that was updated

bool coap_request_is_observe(const struct coap_packet *request)

Returns if this request is enabling observing a resource.

Return
True if the request is enabling observing a resource, False otherwise
Parameters
  • request: Request to be checked

int coap_packet_append_payload_marker(struct coap_packet *cpkt)

Append payload marker to CoAP packet.

Return
0 in case of success or negative in case of error.
Parameters
  • cpkt: Packet to append the payload marker (0xFF)

int coap_packet_append_payload(struct coap_packet *cpkt, u8_t *payload, u16_t payload_len)

Append payload to CoAP packet.

Return
0 in case of success or negative in case of error.
Parameters
  • cpkt: Packet to append the payload
  • payload: CoAP packet payload
  • payload_len: CoAP packet payload len

int coap_packet_append_option(struct coap_packet *cpkt, u16_t code, const u8_t *value, u16_t len)

Appends an option to the packet.

Note: options must be added in numeric order of their codes. Otherwise error will be returned. TODO: Add support for placing options according to its delta value.

Return
0 in case of success or negative in case of error.
Parameters
  • cpkt: Packet to be updated
  • code: Option code to add to the packet, see coap_option_num
  • value: Pointer to the value of the option, will be copied to the packet
  • len: Size of the data to be added

unsigned int coap_option_value_to_int(const struct coap_option *option)

Converts an option to its integer representation.

Assumes that the number is encoded in the network byte order in the option.

Return
The integer representation of the option
Parameters
  • option: Pointer to the option value, retrieved by coap_find_options()

int coap_append_option_int(struct coap_packet *cpkt, u16_t code, unsigned int val)

Appends an integer value option to the packet.

The option must be added in numeric order of their codes, and the least amount of bytes will be used to encode the value.

Return
0 in case of success or negative in case of error.
Parameters
  • cpkt: Packet to be updated
  • code: Option code to add to the packet, see coap_option_num
  • val: Integer value to be added

int coap_find_options(const struct coap_packet *cpkt, u16_t code, struct coap_option *options, u16_t veclen)

Return the values associated with the option of value code.

Return
The number of options found in packet matching code, negative on error.
Parameters
  • cpkt: CoAP packet representation
  • code: Option number to look for
  • options: Array of coap_option where to store the value of the options found
  • veclen: Number of elements in the options array

static u16_t coap_block_size_to_bytes(enum coap_block_size block_size)

Helper for converting the enumeration to the size expressed in bytes.

Return
The size in bytes that the block_size represents
Parameters
  • block_size: The block size to be converted

int coap_block_transfer_init(struct coap_block_context *ctx, enum coap_block_size block_size, size_t total_size)

Initializes the context of a block-wise transfer.

Return
0 in case of success or negative in case of error.
Parameters
  • ctx: The context to be initialized
  • block_size: The size of the block
  • total_size: The total size of the transfer, if known

int coap_append_block1_option(struct coap_packet *cpkt, struct coap_block_context *ctx)

Append BLOCK1 option to the packet.

Return
0 in case of success or negative in case of error.
Parameters
  • cpkt: Packet to be updated
  • ctx: Block context from which to retrieve the information for the Block1 option

int coap_append_block2_option(struct coap_packet *cpkt, struct coap_block_context *ctx)

Append BLOCK2 option to the packet.

Return
0 in case of success or negative in case of error.
Parameters
  • cpkt: Packet to be updated
  • ctx: Block context from which to retrieve the information for the Block2 option

int coap_append_size1_option(struct coap_packet *cpkt, struct coap_block_context *ctx)

Append SIZE1 option to the packet.

Return
0 in case of success or negative in case of error.
Parameters
  • cpkt: Packet to be updated
  • ctx: Block context from which to retrieve the information for the Size1 option

int coap_append_size2_option(struct coap_packet *cpkt, struct coap_block_context *ctx)

Append SIZE2 option to the packet.

Return
0 in case of success or negative in case of error.
Parameters
  • cpkt: Packet to be updated
  • ctx: Block context from which to retrieve the information for the Size2 option

int coap_update_from_block(const struct coap_packet *cpkt, struct coap_block_context *ctx)

Retrieves BLOCK{1,2} and SIZE{1,2} from cpkt and updates ctx accordingly.

Return
0 in case of success or negative in case of error.
Parameters
  • cpkt: Packet in which to look for block-wise transfers options
  • ctx: Block context to be updated

size_t coap_next_block(const struct coap_packet *cpkt, struct coap_block_context *ctx)

Updates ctx so after this is called the current entry indicates the correct offset in the body of data being transferred.

Return
The offset in the block-wise transfer, 0 if the transfer has finished.
Parameters
  • cpkt: Packet in which to look for block-wise transfers options
  • ctx: Block context to be updated

u8_t coap_header_get_version(const struct coap_packet *cpkt)

Returns the version present in a CoAP packet.

Return
the CoAP version in packet
Parameters
  • cpkt: CoAP packet representation

u8_t coap_header_get_type(const struct coap_packet *cpkt)

Returns the type of the CoAP packet.

Return
the type of the packet
Parameters
  • cpkt: CoAP packet representation

u8_t coap_header_get_token(const struct coap_packet *cpkt, u8_t *token)

Returns the token (if any) in the CoAP packet.

Return
Token length in the CoAP packet.
Parameters
  • cpkt: CoAP packet representation
  • token: Where to store the token

u8_t coap_header_get_code(const struct coap_packet *cpkt)

Returns the code of the CoAP packet.

Return
the code present in the packet
Parameters
  • cpkt: CoAP packet representation

u16_t coap_header_get_id(const struct coap_packet *cpkt)

Returns the message id associated with the CoAP packet.

Return
the message id present in the packet
Parameters
  • cpkt: CoAP packet representation

static u16_t coap_next_id(void)

Helper to generate message ids.

Return
a new message id

struct net_buf *coap_packet_get_payload(const struct coap_packet *cpkt, u16_t *offset, u16_t *len)

Returns the fragment pointer and offset where payload starts in the CoAP packet.

Return
the net_buf fragment pointer and offset value if payload exists NULL pointer and offset set to 0 in case there is no payload NULL pointer and offset value 0xffff in case of an error
Parameters
  • cpkt: CoAP packet representation
  • offset: Stores the offset value where payload starts
  • len: Total length of CoAP payload

u8_t *coap_next_token(void)

Returns a randomly generated array of 8 bytes, that can be used as a message’s token.

Return
a 8-byte pseudo-random token.

int coap_well_known_core_get(struct coap_resource *resource, struct coap_packet *request, struct coap_packet *response, struct net_pkt *pkt)
struct coap_resource
#include <coap.h>

Description of CoAP resource.

CoAP servers often want to register resources, so that clients can act on them, by fetching their state or requesting updates to them.

struct coap_observer
#include <coap.h>

Represents a remote device that is observing a local resource.

struct coap_packet
#include <coap.h>

Representation of a CoAP packet.

struct coap_pending
#include <coap.h>

Represents a request awaiting for an acknowledgment (ACK).

struct coap_reply
#include <coap.h>

Represents the handler for the reply of a request, it is also used when observing resources.

struct coap_option
#include <coap.h>

Represents the value of a CoAP option.

To be used with coap_find_options().

struct coap_block_context
#include <coap.h>

Represents the current state of a block-wise transaction.

struct coap_core_metadata
#include <coap_link_format.h>

In case you want to add attributes to the resources included in the ‘well-known/core’ “virtual” resource, the ‘user_data’ field should point to a valid coap_core_metadata structure.

DNS Resolve

group dns_resolve

DNS resolving library.

Defines

DNS_MAX_NAME_SIZE
CONFIG_DNS_RESOLVER_MAX_SERVERS
CONFIG_DNS_NUM_CONCUR_QUERIES
MDNS_SERVER_COUNT
LLMNR_SERVER_COUNT
DNS_MAX_MCAST_SERVERS

Typedefs

typedef dns_resolve_cb_t

DNS resolve callback.

The DNS resolve callback is called after a successful DNS resolving. The resolver can call this callback multiple times, one for each resolved address.

Parameters
  • status: The status of the query: DNS_EAI_INPROGRESS returned for each resolved address DNS_EAI_ALLDONE mark end of the resolving, info is set to NULL in this case DNS_EAI_CANCELED if the query was canceled manually or timeout happened DNS_EAI_FAIL if the name cannot be resolved by the server DNS_EAI_NODATA if there is no such name other values means that an error happened.
  • info: Query results are stored here.
  • user_data: The user data given in dns_resolve_name() call.

Enums

enum dns_query_type

DNS query type enum

Values:

DNS_QUERY_TYPE_A = 1
DNS_QUERY_TYPE_AAAA = 28
enum dns_resolve_status

Status values for the callback.

Values:

DNS_EAI_BADFLAGS = -1
DNS_EAI_NONAME = -2
DNS_EAI_AGAIN = -3
DNS_EAI_FAIL = -4
DNS_EAI_NODATA = -5
DNS_EAI_FAMILY = -6
DNS_EAI_SOCKTYPE = -7
DNS_EAI_SERVICE = -8
DNS_EAI_ADDRFAMILY = -9
DNS_EAI_MEMORY = -10
DNS_EAI_SYSTEM = -11
DNS_EAI_OVERFLOW = -12
DNS_EAI_INPROGRESS = -100
DNS_EAI_CANCELED = -101
DNS_EAI_NOTCANCELED = -102
DNS_EAI_ALLDONE = -103
DNS_EAI_IDN_ENCODE = -105

Functions

int dns_resolve_init(struct dns_resolve_context *ctx, const char *dns_servers_str[], const struct sockaddr *dns_servers_sa[])

Init DNS resolving context.

This function sets the DNS server address and initializes the DNS context that is used by the actual resolver. DNS server addresses can be specified either in textual form, or as struct sockaddr (or both). Note that the recommended way to resolve DNS names is to use the dns_get_addr_info() API. In that case user does not need to call dns_resolve_init() as the DNS servers are already setup by the system.

Return
0 if ok, <0 if error.
Parameters
  • ctx: DNS context. If the context variable is allocated from the stack, then the variable needs to be valid for the whole duration of the resolving. Caller does not need to fill the variable beforehand or edit the context afterwards.
  • dns_servers_str: DNS server addresses using textual strings. The array is NULL terminated. The port number can be given in the string. Syntax for the server addresses with or without port numbers: IPv4 : 10.0.9.1 IPv4 + port : 10.0.9.1:5353 IPv6 : 2001:db8::22:42 IPv6 + port : [2001:db8::22:42]:5353
  • dns_servers_sa: DNS server addresses as struct sockaddr. The array is NULL terminated. Port numbers are optional in struct sockaddr, the default will be used if set to 0.

int dns_resolve_close(struct dns_resolve_context *ctx)

Close DNS resolving context.

This releases DNS resolving context and marks the context unusable. Caller must call the dns_resolve_init() again to make context usable.

Return
0 if ok, <0 if error.
Parameters
  • ctx: DNS context

int dns_resolve_cancel(struct dns_resolve_context *ctx, u16_t dns_id)

Cancel a pending DNS query.

This releases DNS resources used by a pending query.

Return
0 if ok, <0 if error.
Parameters
  • ctx: DNS context
  • dns_id: DNS id of the pending query

int dns_resolve_name(struct dns_resolve_context *ctx, const char *query, enum dns_query_type type, u16_t *dns_id, dns_resolve_cb_t cb, void *user_data, s32_t timeout)

Resolve DNS name.

This function can be used to resolve e.g., IPv4 or IPv6 address. Note that this is asynchronous call, the function will return immediately and system will call the callback after resolving has finished or timeout has occurred. We might send the query to multiple servers (if there are more than one server configured), but we only use the result of the first received response.

Return
0 if resolving was started ok, < 0 otherwise
Parameters
  • ctx: DNS context
  • query: What the caller wants to resolve.
  • type: What kind of data the caller wants to get.
  • dns_id: DNS id is returned to the caller. This is needed if one wishes to cancel the query. This can be set to NULL if there is no need to cancel the query.
  • cb: Callback to call after the resolving has finished or timeout has happened.
  • user_data: The user data.
  • timeout: The timeout value for the query. Possible values: K_FOREVER: the query is tried forever, user needs to cancel it manually if it takes too long time to finish >0: start the query and let the system timeout it after specified ms

struct dns_resolve_context *dns_resolve_get_default(void)

Get default DNS context.

The system level DNS context uses DNS servers that are defined in project config file. If no DNS servers are defined by the user, then resolving DNS names using default DNS context will do nothing. The configuration options are described in subsys/net/lib/dns/Kconfig file.

Return
Default DNS context.

static int dns_get_addr_info(const char *query, enum dns_query_type type, u16_t *dns_id, dns_resolve_cb_t cb, void *user_data, s32_t timeout)

Get IP address info from DNS.

This function can be used to resolve e.g., IPv4 or IPv6 address. Note that this is asynchronous call, the function will return immediately and system will call the callback after resolving has finished or timeout has occurred. We might send the query to multiple servers (if there are more than one server configured), but we only use the result of the first received response. This variant uses system wide DNS servers.

Return
0 if resolving was started ok, < 0 otherwise
Parameters
  • query: What the caller wants to resolve.
  • type: What kind of data the caller wants to get.
  • dns_id: DNS id is returned to the caller. This is needed if one wishes to cancel the query. This can be set to NULL if there is no need to cancel the query.
  • cb: Callback to call after the resolving has finished or timeout has happened.
  • user_data: The user data.
  • timeout: The timeout value for the connection. Possible values: K_FOREVER: the query is tried forever, user needs to cancel it manually if it takes too long time to finish >0: start the query and let the system timeout it after specified ms

static int dns_cancel_addr_info(u16_t dns_id)

Cancel a pending DNS query.

This releases DNS resources used by a pending query.

Return
0 if ok, <0 if error.
Parameters
  • dns_id: DNS id of the pending query

struct dns_addrinfo
#include <dns_resolve.h>

Address info struct is passed to callback that gets all the results.

struct dns_resolve_context
#include <dns_resolve.h>

DNS resolve context structure.

HTTP

group http

HTTP client and server library.

Defines

HTTP_CRLF
http_change_state(ctx, new_state)
http_server_conn_foreach(...)
http_server_conn_monitor(...)
http_server_conn_add(...)
http_server_conn_del(...)

Typedefs

typedef http_url_cb_t

Default URL callback.

This callback is called if there is a connection to unknown URL.

Return
HTTP_VERDICT_DROP if connection is to be dropped, HTTP_VERDICT_ACCEPT if the application wants to accept the unknown URL.
Parameters
  • ctx: The context to use.
  • type: Connection type (websocket or HTTP)
  • dst: Remote socket address

typedef http_recv_cb_t

Network data receive callback.

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

Parameters
  • ctx: The context to use.
  • pkt: Network buffer that is received. If the pkt is not NULL, then the callback will own the buffer and it needs to to unref the pkt as soon as it has finished working with it. On EOF, pkt 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 pkt parameter is set to NULL.
  • flags: Flags related to http. For example contains information if the data is text or binary etc.
  • dst: Remote socket address from where HTTP packet is received.
  • user_data: The user data given in init call.

typedef http_connect_cb_t

Connection callback.

The connect callback is called after there was a connection to non-default URL.

Parameters
  • ctx: The context to use.
  • type: Connection type (websocket or HTTP)
  • dst: Remote socket address where the connection is established.
  • user_data: The user data given in init call.

typedef http_send_cb_t

Network data send callback.

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

Parameters
  • ctx: 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.
  • user_data_send: The user data given in http_send() call.
  • user_data: The user data given in init call.

typedef http_close_cb_t

Close callback.

The close callback is called after a connection was shutdown.

Parameters
  • ctx: The context to use.
  • status: Error code for the closing.
  • user_data: The user data given in init call.

Enums

enum http_state

Values:

HTTP_STATE_CLOSED
HTTP_STATE_WAITING_HEADER
HTTP_STATE_RECEIVING_HEADER
HTTP_STATE_HEADER_RECEIVED
HTTP_STATE_OPEN
enum http_url_flags

Values:

HTTP_URL_STANDARD = 0
HTTP_URL_WEBSOCKET
enum http_connection_type

Values:

HTTP_CONNECTION = 1
WS_CONNECTION
enum http_verdict

Values:

HTTP_VERDICT_DROP
HTTP_VERDICT_ACCEPT

Functions

static int http_server_init(struct http_ctx *ctx, struct http_server_urls *urls, struct sockaddr *server_addr, u8_t *request_buf, size_t request_buf_len, const char *server_banner)
static int http_server_enable(struct http_ctx *ctx)
static int http_server_disable(struct http_ctx *ctx)
static struct http_root_url *http_server_add_url(struct http_server_urls *urls, const char *url, u8_t flags)
int http_close(struct http_ctx *ctx)

Close a network connection to peer.

Return
0 if ok, <0 if error.
Parameters
  • ctx: Http context.

int http_release(struct http_ctx *ctx)

Release this http context.

No network data will be received via this context after this call.

Return
0 if ok, <0 if error.
Parameters
  • ctx: Http context.

int http_set_cb(struct http_ctx *ctx, http_connect_cb_t connect_cb, http_recv_cb_t recv_cb, http_send_cb_t send_cb, http_close_cb_t close_cb)

Set various callbacks that are called at various stage of ws session.

Return
0 if ok, <0 if error.
Parameters
  • ctx: Http context.
  • connect_cb: Connect callback.
  • recv_cb: Data receive callback.
  • send_cb: Data sent callback.
  • close_cb: Close callback.

int http_send_msg_raw(struct http_ctx *ctx, struct net_pkt *pkt, void *user_send_data)

Send a message to peer. The data can be either HTTP or websocket data.

This does not modify the network packet but sends it as is.

Return
0 if ok, <0 if error.
Parameters
  • ctx: Http context.
  • pkt: Network packet to send
  • user_send_data: User specific data to this connection. This is passed as a parameter to sent cb after the packet has been sent.

int http_prepare_and_send(struct http_ctx *ctx, const char *payload, size_t payload_len, const struct sockaddr *dst, void *user_send_data)

Prepare HTTP data to be sent to peer. If there is enough data, the function will then send it too.

Return
0 if ok, <0 if error.
Parameters
  • ctx: Http context.
  • payload: Application data to send
  • payload_len: Length of application data
  • dst: Remote socket address
  • user_send_data: User specific data to this connection. This is passed as a parameter to sent cb after the packet has been sent.

int http_send_chunk(struct http_ctx *ctx, const char *payload, size_t payload_len, const struct sockaddr *dst, void *user_send_data)

Send HTTP data chunk to peer.

Return
0 if ok, <0 if error.
Parameters
  • ctx: Http context.
  • payload: Application data to send
  • payload_len: Length of application data
  • dst: Remote socket address
  • user_send_data: User specific data to this connection. This is passed as a parameter to sent cb after the packet has been sent.

int http_send_flush(struct http_ctx *ctx, void *user_send_data)

Send any pending data immediately.

Return
0 if ok, <0 if error.
Parameters
  • ctx: Http context.
  • user_send_data: Optional user_data for that is used as a parameter in send callback if that is specified.

int http_send_error(struct http_ctx *ctx, int code, u8_t *html_payload, size_t html_len, const struct sockaddr *dst)

Send HTTP error message to peer.

Return
0 if ok, <0 if error.
Parameters
  • ctx: Http context.
  • code: HTTP error code
  • html_payload: Extra payload, can be null
  • html_len: Payload length
  • dst: Remote socket address

int http_add_header(struct http_ctx *ctx, const char *http_header_field, const struct sockaddr *dst, void *user_send_data)

Add HTTP header field to the message.

This can be called multiple times to add pieces of HTTP header fields into the message. Caller must put the “\r\n” characters to the input http_header_field variable.

Return
<0 if error, other value tells how many bytes were added
Parameters
  • ctx: Http context.
  • http_header_field: All or part of HTTP header to be added.
  • dst: Remote socket address.
  • user_send_data: User data value that is used in send callback. Note that this value is only used if this function call causes a HTTP message to be sent.

int http_add_header_field(struct http_ctx *ctx, const char *name, const char *value, const struct sockaddr *dst, void *user_send_data)

Add HTTP header field to the message.

This can be called multiple times to add pieces of HTTP header fields into the message. If name is “Foo” and value is “bar”, then this function will add “Foo: bar\r\n” to message.

Return
<0 if error, other value tells how many bytes were added
Parameters
  • ctx: Http context.
  • name: Name of the header field
  • value: Value of the header field
  • dst: Remote socket address
  • user_send_data: User data value that is used in send callback. Note that this value is only used if this function call causes a HTTP message to be sent.

struct http_root_url *http_url_find(struct http_ctx *ctx, enum http_url_flags flags)

Find a handler function for a given URL.

This is internal function, do not call this from application.

Return
URL handler or NULL if no such handler was found.
Parameters
  • ctx: Http context.
  • flags: Tells if the URL is either HTTP or websocket URL

struct http_cb
#include <http.h>

Websocket and HTTP callbacks

struct http_ctx
#include <http.h>

Http context information. This contains all the data that is needed when working with http API.

Websocket

group websocket

Websocket library.

Defines

WS_FLAG_FINAL

Values for flag variable in HTTP receive callback

WS_FLAG_TEXT
WS_FLAG_BINARY
WS_FLAG_CLOSE
WS_FLAG_PING
WS_FLAG_PONG

Enums

enum ws_opcode

Values:

WS_OPCODE_CONTINUE = 0x00
WS_OPCODE_DATA_TEXT = 0x01
WS_OPCODE_DATA_BINARY = 0x02
WS_OPCODE_CLOSE = 0x08
WS_OPCODE_PING = 0x09
WS_OPCODE_PONG = 0x0A

Functions

int ws_send_msg(struct http_ctx *ctx, u8_t *payload, size_t payload_len, enum ws_opcode opcode, bool mask, bool final, const struct sockaddr *dst, void *user_send_data)

Send websocket msg to peer.

The function will automatically add websocket header to the message.

Return
0 if ok, <0 if error.
Parameters
  • ctx: Websocket context.
  • payload: Websocket data to send.
  • payload_len: Length of the data to be sent.
  • opcode: Operation code (text, binary, ping, pong, close)
  • mask: Mask the data, see RFC 6455 for details
  • final: Is this final message for this message send. If final == false, then the first message must have valid opcode and subsequent messages must have opcode WS_OPCODE_CONTINUE. If final == true and this is the only message, then opcode should have proper opcode (text or binary) set.
  • dst: Remote socket address
  • user_send_data: User specific data to this connection. This is passed as a parameter to sent cb after the packet has been sent.

static int ws_send_msg_to_client(struct http_ctx *ctx, u8_t *payload, size_t payload_len, enum ws_opcode opcode, bool final, const struct sockaddr *dst, void *user_send_data)

Send message to client.

The function will automatically add websocket header to the message.

Return
0 if ok, <0 if error.
Parameters
  • ctx: Websocket context.
  • payload: Websocket data to send.
  • payload_len: Length of the data to be sent.
  • opcode: Operation code (text, binary, ping ,pong ,close)
  • final: Is this final message for this data send
  • dst: Remote socket address
  • user_send_data: User specific data to this connection. This is passed as a parameter to sent cb after the packet has been sent.

Websocket console

group websocket_console

Websocket console library.

Functions

int ws_console_enable(struct http_ctx *ctx)

Enable websocket console.

The console can be sent over websocket to browser.

Return
0 if ok, <0 if error
Parameters
  • ctx: HTTP context

int ws_console_disable(struct http_ctx *ctx)

Disable websocket console.

Return
0 if ok, <0 if error
Parameters
  • ctx: HTTP context

int ws_console_recv(struct http_ctx *ctx, struct net_pkt *pkt)

Receive data from outside system and feed it into Zephyr.

Return
0 if ok, <0 if error
Parameters
  • ctx: HTTP context
  • pkt: Network packet containing the received data.