欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LwIP之netbuf

程序员文章站 2024-02-22 18:48:46
...

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

LwIP之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