lwip-udp

2019-07-14 11:01发布

UDP编程虽然不难,但是有很多不懂得地方。
第一个就是UDP的块,udp_pcb主要是记录udp的信息,如本地IP,端口号,远程IP,远程端口号,recv函数,和自定义参数args。
这里写图片描述
一个程序中一般有多个控制块,这些控制块通过next指针连接在一起,但接收到一个数据块时就会遍历这些udp_pcb控制块,找到符合的控制块,接着调用recv中的回调函数进行处理。 第二个就是一些操作函数。 第一个就是udp_new()
udp_new() – Create a new UDP pcb Synopsis struct udp_pcb *udp_new(void); Description Creates a new connection identifier (PCB) which can be used for UDP
communication. The PCB is not active until it has either been bound to
a local address or connected to a remote address. Return value Returns the new PCB. If memory is not available for creating the new
PCB, NULL is returned.
(2)第二个是绑定函数udp_bind
udp_bind() – Bind PCB to local IP address and port Synopsis err_t udp_bind(struct udp_pcb *pcb, struct ip_addr *ipaddr, u16_t port); Description Binds pcb to the local address indicated by ipaddr and port indicated
by port. ipaddr can be IP_ADDR_ANY to indicate that it should listen
to any local IP address. Port may be 0 for any port. Return value This function can return ERR_USE if all usable UDP dynamic ports are
used (only relevant if port is 0. Otherwise udp_bind() will always
return ERR_OK.
(3)第三个是连接函数udp_connect()
udp_connect() – Set remote UDP peer Synopsis err_t udp_connect(struct udp_pcb *pcb, struct ip_addr *ipaddr, u16_t port); Description Sets the remote end of pcb. This function does not generate any
network traffic, but only sets the remote address of the pcb. Return value This function can return ERR_USE if all usable UDP dynamic
ports are used. Otherwise udp_connect() will always return ERR_OK.
(4)第四个是发送数据函数udp_send()
udp_send() – Send UDP packet Synopsis err_t udp_send(struct udp_pcb *pcb, struct pbuf *p); Description Sends the pbuf p to the remote host associated with pcb. The pbuf is
not deallocated. Return value This function returns ERR_OK on success; but may return ERR_MEM if
there is insufficient memory to prepend a UDP header, or ERR_RTE if no
suitable outgoing network interface could be found to route the packet
on.
send和sendto的区别是sendto需要添加远程ip地址和端口。 (5)第五个是udp_recv()函数,这是一个非常重要的函数。
udp_recv() – Set callback for incoming UDP data Synopsis void udp_recv(struct udp_pcb *pcb, err_t (*recv) (void *arg, struct
udp_pcb *upcb, struct pbuf *p, struct ip_addr *addr, u16_t port), void
*recv_arg); Description Registers a callback function recv with the PCB pcb so that when a UDP
datagram is received, the callback is invoked. The callback argument
arg is set as the argument recv_arg to udp_recv(). The received
datagram packet buffer is held in p. The source address of the
datagram is provided in addr, and the source port in port. The
callback is expected to free the packet.
recv函数中的第二参数是一个函数指针,但接收到数据的时候,就会调用这个函数指针指向的函数,其实就是一个回调函数。这个回调函数有5个参数,分别是:arg表示传递给函数的自定义数据;pcb指向接收到报文的UDP控制块结构;p指向接收到的报文pbuf;addr表示发送该报文的源主机的IP地址;port表示发送该报文的源主机端口。