欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

LwIP之netbuf

发布时间:2025/3/15 编程问答 48 豆豆
生活随笔 收集整理的这篇文章主要介绍了 LwIP之netbuf 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

 netbuf是应用程序和协议栈内核交互的一种数据结构

netbuf并不复杂,下面是实现代码

/* 创建netbuf */ struct netbuf *netbuf_new(void) {struct netbuf *buf;/* 为netbuf申请内存空间 */buf = (struct netbuf *)memp_malloc(MEMP_NETBUF);if(buf != NULL) {/* 清空参数 */buf->p = NULL;buf->ptr = NULL;ip_addr_set_any(&buf->addr);buf->port = 0;return buf;} else {return NULL;} }/* 删除netbuf */ void netbuf_delete(struct netbuf *buf) {if(buf != NULL) {/* 先释放pbuf */if(buf->p != NULL) {pbuf_free(buf->p);buf->p = buf->ptr = NULL;}/* 再释放netbuf */memp_free(MEMP_NETBUF, buf);} }/* 为netbuf申请数据(pbuf)空间 */ void *netbuf_alloc(struct netbuf *buf, u16_t size) {/* 为netbuf申请数据(pbuf)空间 */if(buf->p != NULL) {pbuf_free(buf->p);}buf->p = pbuf_alloc(PBUF_TRANSPORT, size, PBUF_RAM);if(buf->p == NULL) {return NULL;}/* ptr指针初始化指向第一个pbuf */buf->ptr = buf->p;/* 返回数据有效数据指针 */return buf->p->payload; }/* 释放netbuf的数据(pbuf)空间 */ void netbuf_free(struct netbuf *buf) {if(buf->p != NULL) {pbuf_free(buf->p);}buf->p = buf->ptr = NULL; }/* 为netbuf申请PBUF_REF型pbuf内存,指向已存在RAM */ err_t netbuf_ref(struct netbuf *buf, const void *dataptr, u16_t size) {if(buf->p != NULL) {pbuf_free(buf->p);}buf->p = pbuf_alloc(PBUF_TRANSPORT, 0, PBUF_REF);if(buf->p == NULL) {buf->ptr = NULL;return ERR_MEM;}buf->p->payload = (void *)dataptr;buf->p->len = buf->p->tot_len = size;buf->ptr = buf->p;return ERR_OK; }/* 将两个netbuf拼接起来 */ void netbuf_chain(struct netbuf *head, struct netbuf *tail) {pbuf_cat(head->p, tail->p);head->ptr = head->p;memp_free(MEMP_NETBUF, tail); }/* 获取netbuf有效数据指针和数据长度 */ err_t netbuf_data(struct netbuf *buf, void **dataptr, u16_t *len) {if(buf->ptr == NULL) {return ERR_BUF;}*dataptr = buf->ptr->payload;*len = buf->ptr->len;return ERR_OK; }/* 向后偏移netbuf的pbuf偏移指针 */ s8_t netbuf_next(struct netbuf *buf) {if(buf->ptr->next == NULL) {return -1;}buf->ptr = buf->ptr->next;if(buf->ptr->next == NULL) {return 1;}return 0; }/* netbuf的pbuf偏移指针指向第一个pbuf */ void netbuf_first(struct netbuf *buf) {buf->ptr = buf->p; }

 

总结

以上是生活随笔为你收集整理的LwIP之netbuf的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。