Can't recive data by recvfrom
Posted: 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);
}
}