lwip ping功能实现

lwip ping功能实现,第1张

lwip ping功能实现
static baseType_t prvPingCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
	const char *pcParameter;
	baseType_t xParameterStringLength;
	static UbaseType_t uxParameterNumber = 0;
	
	(void)pcCommandString;
	(void)xWriteBufferLen;
	configASSERT(pcWriteBuffer);

	if (!ping_mutex)
	{
		ping_mutex = xSemaphoreCreateBinary();
	}

	pcWriteBuffer[0] = 0;

	static struct raw_pcb *ping_pcb = NULL;
	ip_addr_t ipaddr;

	if (!ping_pcb)
	{
		ping_pcb = raw_new(IP_PROTO_ICMP);
		raw_recv(ping_pcb, raw_ping_callback, pcWriteBuffer);
		raw_bind(ping_pcb, IP_ADDR_ANY);
	}
	else
	{
		vTaskDelay(1000);
	}

	pcParameter = FreeRTOS_CLIGetParameter(
		pcCommandString,		
		1,						
		&xParameterStringLength 
	);

	if (pcParameter == NULL)
	{
		sprintf(pcWriteBuffer, "Ip address is lackrn");
		return pdFALSE;
	}

	if (ipaddr_aton(pcParameter, &ipaddr) == 0)
	{
		if (netconn_gethostbyname(pcParameter, &ipaddr) != 0)
		{
			sprintf(pcWriteBuffer, "Ip address is invalidrn");
			return pdFALSE;
		}
	}

	ping_send(ping_pcb, &ipaddr);

	if (xSemaphoreTake(ping_mutex, 1000) != pdPASS)
	{
		sprintf(pcWriteBuffer, "unreachable....rn");
	}

	uxParameterNumber++;
	if (uxParameterNumber == 4)
	{
		uxParameterNumber = 0;
		return pdFALSE;
	}

	return pdTRUE;
}

void ping_send(struct raw_pcb *pcb, ip_addr_t *ipaddr)
{
	struct pbuf *p;
	struct icmp_echo_hdr *iecho;
	p = pbuf_alloc(PBUF_IP, 40, PBUF_RAM); //申请pbuf结构
	if (!p)
	{
		return;
	}
	if (p->len == p->tot_len && p->next == NULL)
	{
		iecho = (struct icmp_echo_hdr *)p->payload;
		ping_prepare_echo(iecho, 40); //填写ICMP首部字段
		raw_sendto(pcb, p, ipaddr);	  //底层发送
	}

	pbuf_free(p);
}


int raw_ping_callback(void *arg, struct raw_pcb *pcb, struct pbuf *p, ip_addr_t *addr)
{
	char *buf = (char *)arg;
	if (!buf)
	{
		return 0;
	}

	struct ip_hdr *iphdr;
	if (p->tot_len >= (PBUF_IP_HLEN + 8))
	{
		iphdr = (struct ip_hdr *)((u8_t *)p->payload);
		sprintf((char *)buf, "Come from %d.%d.%d.%d to reply ..OK..rn", *(char *)addr, *((char *)addr + 1), *((char *)addr + 2), *((char *)addr + 3));
	}

	if (__get_IPSR() != 0)
	{
		baseType_t xHigherPriorityTaskWoken = pdFALSE;
		if (ping_mutex)
		{
			xSemaphoreGiveFromISR(ping_mutex, &xHigherPriorityTaskWoken);
		}
		portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
	}
	else
	{
		if (ping_mutex)
		{
			xSemaphoreGive(ping_mutex);
		}
	}

	return 0;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5580104.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存