基于LWIP的UDP实例
本工程硬件基于STM32F429+LAN8720A外设,使用RMII通信接口。工程由STM32CUBEMX直接生成。代码主要使用的是ST官方例程。
//定义端口号
#define UDP_SERVER_PORT 7 /* define the UDP local connection port */
#define UDP_CLIENT_PORT 7 /* define the UDP remote connection port */
//声明接收数据回调函数,在初始化函数中指定
void udp_echoserver_receive_callback(void *arg, struct udp_pcb *upcb, struct pbuf *p, const ip_addr_t *addr, u16_t port);
//UDP服务器端初始化函数
void udp_echoserver_init(void)
{
struct udp_pcb *upcb;
err_t err;
/* Create a new UDP control block */
upcb = udp_new(); //创建一个新的UDP控制块
if (upcb)
{
/* Bind the upcb to the UDP_PORT port */
/* Using IP_ADDR_ANY allow the upcb to be used by any local interface */
err = udp_bind(upcb, IP_ADDR_ANY, UDP_SERVER_PORT); //绑定本地IP地址及端口
if(err == ERR_OK)
{
/* Set a receive callback for the upcb */
udp_recv(upcb, udp_echoserver_receive_callback, NULL); //注册接收数据回调函数
}
else
{
udp_remove(upcb);
}
}
}
//服务器端接收数据回调函数
void udp_echoserver_receive_callback(void *arg, struct udp_pcb *upcb, struct pbuf *p, const ip_addr_t *addr, u16_t port)
{
/* Tell the client that we have accepted it */
udp_sendto(upcb, p,addr,port); //回显数据
/* Free the p buffer */
pbuf_free(p);
}
在main.c文件中,在LWIP初始化之后,增加服务器端初始化函数,即可实现服务器端功能,实现数据回显功能。
udp_echoserver_init();
//接收数据回调函数声明
void udp_receive_callback(void *arg, struct udp_pcb *upcb, struct pbuf *p, const ip_addr_t *addr, u16_t port);
u8_t data[100]={0x00}; //数据buffer初始化
__IO uint32_t message_count = 0;
struct udp_pcb *upcb; //UDP控制块初始化
//UDP客户端连接函数
void udp_echoclient_connect(void)
{
ip_addr_t DestIPaddr;
err_t err;
/*assign destination IP address */
IP4_ADDR( &DestIPaddr, 192, 168, 1, 103 ); //设置服务器端的IP地址
/* Create a new UDP control block */
upcb = udp_new(); //创建一个新的UDP控制块
if (upcb!=NULL)
{
/* configure destination IP address and port */
err= udp_connect(upcb, &DestIPaddr, 7); //服务器端地址、端口配置
if (err == ERR_OK)
{
printf("local port is %d\r\n",upcb->local_port);
/* Set a receive callback for the upcb */
udp_recv(upcb, udp_receive_callback, NULL); //注册回调函数
udp_echoclient_send(); //**数据发送,第一次连接时客户端发送数据至服务器端,发送函数中会遍历查找源IP地址的配置,如果源IP地址未配置,则数据发送失败。该处出现的问题在后面总结中提到了**
}
}
}
//客户端数据发送函数
void udp_echoclient_send(void)
{
struct pbuf *p;
sprintf((char*)data, "sending udp client message %d", (int)message_count);
/* allocate pbuf from pool*/
p = pbuf_alloc(PBUF_TRANSPORT,strlen((char*)data), PBUF_POOL);
printf("test1\r\n");
if (p != NULL)
{
printf("test2\r\n");
/* copy data to pbuf */
pbuf_take(p, (char*)data, strlen((char*)data));
/* send udp data */
udp_send(upcb, p); //发送数据
/* free pbuf */
pbuf_free(p);
}
printf("test3\r\n");
}
//客户端接收数据回调函数
void udp_receive_callback(void *arg, struct udp_pcb *upcb, struct pbuf *p, const ip_addr_t *addr, u16_t port)
{
/* send udp data */
udp_send(upcb, p); //数据回显
/* free pbuf */
pbuf_free(p);
}
在main.c文件中,在LWIP初始化之后,增加客户端初始化函数,即可实现客户端功能,实现数据回显功能。
udp_echoclient_connect();