LWIP 要实现DHCP功能步骤:
1)打开DHCP开关: #define LWIP_DHCP 1
2)调用函数 dhcp_start(struct netif *netif)
3)检测是否接收到服务器分配的IP
uint8_t check_DHCP_success(struct netif *netif)
{
if(netif->dhcp->offered_ip_addr.addr!=0&&netif->dhcp->offered_sn_mask.addr!=0&&netif->dhcp->offered_gw_addr.addr!=0&&netif->dhcp->server_ip_addr.addr!=0)
{
IP4_ADDR(&ipaddr,(netif->dhcp->offered_ip_addr.addr&0x000000ff), (netif->dhcp->offered_ip_addr.addr&0x0000ff00)>>8, (netif->dhcp->offered_ip_addr.addr&0x00ff0000)>>16, (netif->dhcp->offered_ip_addr.addr&0xff000000)>>24);
IP4_ADDR(&gw, (netif->dhcp->offered_gw_addr.addr&0x000000ff), (netif->dhcp->offered_gw_addr.addr&0x0000ff00)>>8, (netif->dhcp->offered_gw_addr.addr&0x00ff0000)>>16, (netif->dhcp->offered_gw_addr.addr&0xff000000)>>24);
IP4_ADDR(&netmask, (netif->dhcp->offered_sn_mask.addr&0x000000ff), (netif->dhcp->offered_sn_mask.addr&0x0000ff00)>>8, (netif->dhcp->offered_sn_mask.addr&0x00ff0000)>>16, (netif->dhcp->offered_sn_mask.addr&0xff000000)>>24);
IP4_ADDR(&addrCmdRecv, (netif->dhcp->server_ip_addr.addr&0x000000ff), (netif->dhcp->server_ip_addr.addr&0x0000ff00)>>8, (netif->dhcp->server_ip_addr.addr&0x00ff0000)>>16, (netif->dhcp->server_ip_addr.addr&0xff000000)>>24);
netif_set_addr(netif,&ipaddr, &netmask, &gw);
netif_set_default(netif);
netif_set_up(netif);
return 1;
}
else
return 0;
}
注:由于DHCP采用的是UDP和服务器进行通信,所以有可能需要多次调用函数 dhcp_start(struct netif *netif)