Test scenario 1:
- start up Java receiver on computer A
- start up C receiver on ESP32 A
- execute a send on computer B
Result scenario 1:
- Java receiver gets the message on computer A
- ESP32 A does not get the message
Test scenario 2:
- start up Java receiver on computer A
- start up C receiver on ESP32 A
- execute a send on ESP 32 B
Result scenario 2:
- Java receiver gets the message on ESP32 B
- C receiver on ESP32 A does not get message
Used C receiver code for ESP32 A. I tried multiple variations of UDP multicast programs all with the same result. I assume I miss something obviously?
Code: Select all
int sock;
int flag_on = 1;
struct sockaddr_in multicast_addr;
char message_received[MAX_LEN+1];
int msgrecv_len;
struct ip_mreq mc_req;
char* multicast_ip;
unsigned short multicast_port;
struct sockaddr_in from_addr;
unsigned int from_len;
multicast_ip = "239.255.255.250";
multicast_port = atoi("1900");
if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
{
ESP_LOGE(TAG, "socket() failed");
exit(1);
}
if ((setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &flag_on, sizeof(flag_on))) < 0)
{
ESP_LOGE(TAG, "setsockopt() failed %s", strerror(errno));
exit(1);
}
memset(&multicast_addr, 0, sizeof(multicast_addr));
multicast_addr.sin_family = AF_INET;
multicast_addr.sin_addr.s_addr = htonl(INADDR_ANY);
multicast_addr.sin_port = htons(multicast_port);
if ((bind(sock, (struct sockaddr *) &multicast_addr, sizeof(multicast_addr))) < 0)
{
ESP_LOGE(TAG, "bind() failed");
exit(1);
}
mc_req.imr_multiaddr.s_addr = inet_addr(multicast_ip);
mc_req.imr_interface.s_addr = htonl(INADDR_ANY);
if ((setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (void*) &mc_req, sizeof(mc_req))) < 0)
{
ESP_LOGE(TAG, "setsockopt() failed");
exit(1);
}
while(1)
{
memset(message_received, 0, sizeof(message_received));
from_len = sizeof(from_addr);
memset(&from_addr, 0, from_len);
ESP_LOGI(TAG, "Wait for message");
if ((msgrecv_len = recvfrom(sock, message_received, MAX_LEN, 0, (struct sockaddr*)&from_addr, &from_len)) < 0)
{
ESP_LOGE(TAG, "recvfrom() failed");
break;
}
ESP_LOGI(TAG, "Message received");
ESP_LOGI(TAG, "Received %d bytes from %s: ", msgrecv_len, inet_ntoa(from_addr.sin_addr));
ESP_LOGI(TAG, "%s", message_received);
}