Can't recive data by recvfrom

SuperClark
Posts: 1
Joined: Sun Jul 15, 2018 9:33 am

Can't recive data by recvfrom

Postby SuperClark » Sun Jul 15, 2018 9:45 am

I just want to recive a command data to control an IO, it uses UDP protocol. WIFI is OK. I try to send some data to this port. But the function 'recvfrom' can't get any data. Please give me some help, thank you.

Code: Select all

static void wifi_task() {
	struct sockaddr_in client_addr, local_addr;
	int recved_bytes; // err,
	xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT, false, true, portMAX_DELAY);
	ESP_LOGI(TAG, "Connected to AP");
	int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
	if (sock < 0) {
        ESP_LOGE(TAG, "Failed to create socket. Error %d", errno);
        return;
    }
	tcpip_adapter_ip_info_t ip_info;
    ESP_ERROR_CHECK( tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_STA, &ip_info));
	memset(&local_addr, 0, sizeof local_addr);
	local_addr.sin_family = AF_INET;
	local_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	local_addr.sin_port = htons(1001);
 	if (bind(sock, (struct sockaddr *) &local_addr, sizeof local_addr) < 0) {
        ESP_LOGE(TAG, "bind port error");
        return;
    }
	socklen_t client_addr_len = sizeof(client_addr);
	char* recv_buf = (char*)malloc(100);
	if (recv_buf == 0) {
		ESP_LOGE(TAG, "allocate memory failed");
		return;
	}
	memset(recv_buf, 0, 100);
	ESP_LOGI(TAG, "start to reciving...");
	while (1) {
		memset(&client_addr, 0, sizeof client_addr);
		client_addr.sin_family = AF_INET;
		client_addr.sin_addr.s_addr = htonl(INADDR_ANY);
		client_addr.sin_port = htons(1001);
		client_addr_len = sizeof(client_addr);
		recved_bytes = recvfrom(sock, recv_buf, 2, 0, (struct sockaddr *)&client_addr, &client_addr_len);
		if (recved_bytes > 0) {
			ESP_LOGI(TAG, "recv data %d bytes", recved_bytes);
			gpio_set_level(GPIO_NUM_2, (strcmp(recv_buf, "on") == 0) ? 1 : 0);
			sendto(sock, recv_buf, recved_bytes, 0, (struct sockaddr *)&client_addr, sizeof(client_addr));
			memset(recv_buf, 0, 100);
		}
		vTaskDelay(10 / portTICK_PERIOD_MS);
	}
}

User avatar
fly135
Posts: 606
Joined: Wed Jan 03, 2018 8:33 pm
Location: Orlando, FL

Re: Can't recive data by recvfrom

Postby fly135 » Mon Jul 16, 2018 4:14 pm

Might be worth checking the return code from recvfrom to see if it's returning with any errors in errno.

John A

Who is online

Users browsing this forum: No registered users and 96 guests