fix(tcp_server): Fix TCP server example IPv6 support
static EventGroupHandle_t wifi_event_group;
const int IPV4_GOTIP_BIT = BIT0;
+#ifdef CONFIG_EXAMPLE_IPV6
const int IPV6_GOTIP_BIT = BIT1;
+#endif
static const char *TAG = "example";
@@ -49,8 +51,10 @@ static esp_err_t event_handler(void *ctx, system_event_t *event)
ESP_LOGI(TAG, "SYSTEM_EVENT_STA_START");
break;
case SYSTEM_EVENT_STA_CONNECTED:
+#ifdef CONFIG_EXAMPLE_IPV6
/* enable ipv6 */
tcpip_adapter_create_ip6_linklocal(TCPIP_ADAPTER_IF_STA);
+#endif
break;
case SYSTEM_EVENT_STA_GOT_IP:
xEventGroupSetBits(wifi_event_group, IPV4_GOTIP_BIT);
@@ -60,14 +64,18 @@ static esp_err_t event_handler(void *ctx, system_event_t *event)
/* This is a workaround as ESP32 WiFi libs don't currently auto-reassociate. */
esp_wifi_connect();
xEventGroupClearBits(wifi_event_group, IPV4_GOTIP_BIT);
+#ifdef CONFIG_EXAMPLE_IPV6
xEventGroupClearBits(wifi_event_group, IPV6_GOTIP_BIT);
+#endif
break;
case SYSTEM_EVENT_AP_STA_GOT_IP6:
+#ifdef CONFIG_EXAMPLE_IPV6
xEventGroupSetBits(wifi_event_group, IPV6_GOTIP_BIT);
ESP_LOGI(TAG, "SYSTEM_EVENT_STA_GOT_IP6");
char *ip6 = ip6addr_ntoa(&event->event_info.got_ip6.ip6_info.ip);
ESP_LOGI(TAG, "IPv6: %s", ip6);
+#endif
default:
break;
}
@@ -96,7 +104,11 @@ static void initialise_wifi(void)
static void wait_for_ip()
{
+#ifdef CONFIG_EXAMPLE_IPV6
uint32_t bits = IPV4_GOTIP_BIT | IPV6_GOTIP_BIT;
+#else
+ uint32_t bits = IPV4_GOTIP_BIT;
+#endif
ESP_LOGI(TAG, "Waiting for AP connection...");
xEventGroupWaitBits(wifi_event_group, bits, false, true, portMAX_DELAY);
@@ -151,7 +163,11 @@ static void tcp_server_task(void *pvParameters)
}
ESP_LOGI(TAG, "Socket listening");
+#ifdef CONFIG_EXAMPLE_IPV6
struct sockaddr_in6 sourceAddr; // Large enough for both IPv4 or IPv6
+#else
+ struct sockaddr_in sourceAddr;
+#endif
uint addrLen = sizeof(sourceAddr);
int sock = accept(listen_sock, (struct sockaddr *)&sourceAddr, &addrLen);
if (sock < 0) {
@@ -174,12 +190,16 @@ static void tcp_server_task(void *pvParameters)
}
// Data received
else {
+#ifdef CONFIG_EXAMPLE_IPV6
// Get the sender's ip address as string
if (sourceAddr.sin6_family == PF_INET) {
inet_ntoa_r(((struct sockaddr_in *)&sourceAddr)->sin_addr.s_addr, addr_str, sizeof(addr_str) - 1);
} else if (sourceAddr.sin6_family == PF_INET6) {
inet6_ntoa_r(sourceAddr.sin6_addr, addr_str, sizeof(addr_str) - 1);
}
+#else
+ inet_ntoa_r(((struct sockaddr_in *)&sourceAddr)->sin_addr.s_addr, addr_str, sizeof(addr_str) - 1);
+#endif
rx_buffer[len] = 0; // Null-terminate whatever we received and treat like a string
ESP_LOGI(TAG, "Received %d bytes from %s:", len, addr_str);
