VxWorks 6.8: setsockopt with IP_ADD_MEMBERSHIP returning EADDRNOTAVAIL - sockets

I am trying to set up a socket to receive multicast UDP packets on VxWorks 6.8.
sin.sin_len = (u_char)sizeof (sin);
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
/* UDP port number to match for the received packets */
sin.sin_port = htons (mcastPort);
/* bind a port number to the socket */
if (bind(sockDesc, (struct sockaddr *)&sin, sizeof(sin)) != 0)
{
perror("bind");
status = errno;
goto cleanUp;
}
/* fill in the argument structure to join the multicast group */
/* initialize the multicast address to join */
ipMreq.imr_multiaddr.s_addr = inet_addr (mcastAddr);
/* unicast interface addr from which to receive the multicast packets */
ipMreq.imr_interface.s_addr = inet_addr (ifAddr);
printf ("Interface address on which to receive multicast packets: %s\n", ifAddr);
/* set the socket option to join the MULTICAST group */
int code = setsockopt (sockDesc, IPPROTO_IP, IP_ADD_MEMBERSHIP,
(char *)&ipMreq,
sizeof (ipMreq));
The setsockopt() call is returning -1 and errno is being set to 49 or EADDRNOTAVAIL. On wireshark, when we perform setsockopt I can see a properly formed group unsubscribe packet being sent out from the right port/interface. All different combinations of interfaces, ports, and multicast groups give the same result.
I am unable to debug very far into setsockopt as there doesnt seem to be anything wrong before the task calls ipcom_pipe_send and ipnet_usr_sock_pipe_recv, and after the recv call errno is set. I dont know how to debug the relevant tNetTask code that may be generating the error.

It could be that there's an issue with the interface index you supplied. Define ipMreq to be a struct ip_mreq, which does not have the imr_ifindex, instead of a struct ip_mreqn and remove the ipMreq.imr_ifindex = 2; line.

Related

ESP32 Multicast UDP High losses (receiving)

I'm developing device base on ESP32 module that have a UDP socket open only to receive broadcast packets on one port (7890 to be exact). The problem is that the data losses are high - around 90%. My test setup is:
ESP32 - connected to WiFi network with open UDP receing task (code belowe)
PC connected to the same netwer via LAN with UDP terminal set to brodacast to remote: 192.168.10.255:7890
Mobile phone connected to WiFi with UDP terminal set to brodacast to remote: 192.168.10.255:7890
When I send something from PC or mobile phone there is no data lossage between Mobile phone and PC but ESP32 receive around 10% of data that I transmit from both of senders. If I change from multicast to unicast on PC or Phone to send data to ESP32, it work without problem.
I know that UDP does not guarantee the delivery but 10% efficiency seems for me to be super low, especially when it seems that there is no problem with busy network because PC and mobile received the data all the time.
Do you have any suggestion to the code or some setting that can be changed in menu config ?
At the moment my application have only two tasks:
WiFi Task that after connection is just waiting for event
UDP Task that the code is below
Update 04.07.2018 (13:15)
Problem disappear when I don't initialize bluetooth. Sorry that I didn't mention previously about BT being initialized but I kept me initializing function from my normal program that have a lot more tasks (BT included) and totally forgot about this myself.
Anyway - do you think that there is some issue with sharing the resource or is it some physical interference ? I'm using ESP32-DevKitC that is on the breadboard, so no additional shielding is present.
#define PORT_NUMBER 7890
#define BUFLEN 100
void udp_task(void *pvParameter)
{
struct sockaddr_in clientAddress;
struct sockaddr_in serverAddress;
struct sockaddr_in si_other;
unsigned int slen = sizeof(si_other);
unsigned int recv_len;
char buf[BUFLEN];
int sock;
printf("UDP Task: Opening..\n");
int ret;
ret = UDP_List_Open(&clientAddress, &serverAddress, &sock);
if(ret == 0)
{
printf("UDP Task: Open\n");
}
else
{
printf("UDP Task: Can't open\n");
}
while(1)
{
memset(buf,0,100);
if ((recv_len = recvfrom(sock, buf, 100, 0, (struct sockaddr *) &si_other, &slen)) == -1)
{
printf("UDP error\n");
break;
}
sendto(sock, buf, recv_len, 0, (struct sockaddr *)&si_other, sizeof(si_other));
printf("UDP Task: Received packet from %s:%d\n", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port));
printf("UDP Task: Data: %s -- %d\n" , buf, recv_len);
}
while(1)
{
vTaskDelay(100 / portTICK_RATE_MS);
}
}
int UDP_List_Open(struct sockaddr_in* clientAddress, struct sockaddr_in* serverAddress, int* sock)
{
// Create a socket that we will listen upon.
*sock = socket(AF_INET, SOCK_DGRAM, 0);
if (*sock < 0)
{
printf("UDP List Open: Socket error\n");
return 1;
}
// Bind our server socket to a port.
serverAddress->sin_family = AF_INET;
serverAddress->sin_addr.s_addr = htonl(INADDR_ANY);
serverAddress->sin_port = htons(PORT_NUMBER);
int rc = bind(*sock, serverAddress, sizeof(*serverAddress));
if (rc < 0)
{
printf("UDP List Open: Bind error\n");
return 2;
}
return 0;
}
Even though UDP is considered fire and forget, (unlike TCP), unicast UDP through WiFi is reliable because reliability is built into the WiFi protocol. But this can work for Unicast only because there is one known recipient. Multicast UDP is unreliable because there are no checks and retries.
I had the same problem when I was trying to use multicast UDP with the ESP8266. It caused me to dig deeper into the issue. In the end I use UDP multicast for discovery but then switch to Unicast UDP for subsequent transfers.
See Multicast Wifi Problem Statement
https://tools.ietf.org/id/draft-mcbride-mboned-wifi-mcast-problem-statement-01.html

BSD socket connect + select (client)

There must be something wrong in the below code but I don't seem to be able to use a client connect, non blocking in combination with a select statement. Please ignore the below lack of error handling.
I seem to have two issues
1. select blocks until timeout (60) if I try to connect port 80 on an internet server
2. trying to connect a existing or non existing port on 127.0.0.1 always instantly returns the select with no way to distinction between success or failure to connect.
What am I missing in my understanding of BSD nonblocking in combination with select?
fd_set readfds;
FD_ZERO(&readfds);
struct timeval tv;
tv.tv_sec = 60;
tv.tv_usec = 0;
struct sockaddr_in dest;
int socketFD = socket(AF_INET, SOCK_STREAM, 0);
memset(&dest, 0, sizeof(dest));
dest.sin_family = AF_INET;
dest.sin_addr.s_addr = inet_addr("127.0.0.1");
dest.sin_port = htons(9483);
long arg;
arg = fcntl(socketFD, F_GETFL, NULL);
arg |= O_NONBLOCK;
fcntl(socketFD, F_SETFL, arg);
if (connect(socketFD, (struct sockaddr *)&dest, sizeof(struct sockaddr))<0 && errno == EINPROGRESS) {
//now add it to the read set
FD_SET(socketFD, &readfds);
int res = select(socketFD+1, &readfds, NULL, NULL, &tv);
int error = errno;
if (res>0 && FD_ISSET(socketFD, &readfds)) {
NSLog(#"errno: %d", error); //Always 36
}
}
errno is set in your original attempt to connect -- legitimately: that is, it's in-progress. You then call select. Since select didn't fail, errno is not being reset. System calls only set errno on failure; they do not clear it on success.
The connect may have completed successfully. You aren't checking that though. You should add a call to getsockopt with SO_ERROR to determine whether it worked. This will return the error state on the socket.
One other important note. According to the manual page (https://www.freebsd.org/cgi/man.cgi?query=connect&sektion=2), you should be using the writefds to await completion of the connect. I don't know whether the readfds will correctly report the status.
[EINPROGRESS] The socket is non-blocking and the connection cannot
be completed immediately. It is possible to select(2)
for completion by selecting the socket for writing.
See also this very similar question. Using select() for non-blocking sockets to connect always returns 1

Can't listen on multiple sockets when using BINDTODEVICE?

I have two network links to the Internet, and I have two default routes set up:
Destination Gateway Genmask Flags Metric Ref Use Iface
default gateway0 0.0.0.0 UG 0 0 eth0
default gateway1 0.0.0.0 UG 0 0 eth1
...
I created two sockets with BINDTODEVICE, so that I can send data out either eth0 or eth1. I am also trying to listen on both sockets using recvfrom (UDP data only), but I can only successfully read data from whichever interface is listed first in the routes. eth0 works, for example, but I get nothing from the socket bound to eth1.
Running wireshark on either interface shows data coming in successfully - that is, I can see data being sent from the Internet to either eth0's or eth1's IP in Wireshark (so NAT is not a problem with either), but my program just blocks on recvfrom without getting any data.
I have tried using bind on the sockets to make them listen on their respective interface's IP, and also tried not using bind to have them listen on 0.0.0.0 (each on a different port), but I still have the same problem.
How can I make sure both sockets get the data they're supposed to?
Edit: sample code:
int createDeviceBoundUDPSocket(uint32_t sip, uint16_t sport, const char* bind_dev) {
printf("bind_dev = %s", bind_dev);
int s = socket(AF_INET, SOCK_DGRAM, 0);
int result;
struct sockaddr_in my_ip_addr;
if (s < 0) {
perror("socket");
return s;
}
memset(&my_ip_addr, 0, sizeof(my_ip_addr));
my_ip_addr.sin_family = AF_INET;
my_ip_addr.sin_addr.s_addr = htonl(sip);
my_ip_addr.sin_port = htons(sport);
// commenting this section out doesn't seem to make a difference
// listening on 0.0.0.0 or the interface's IP both have the same problem
result = bind(s, (struct sockaddr*)(&my_ip_addr), sizeof(my_ip_addr));
if (result < 0) {
perror("Error in bind");
return result;
}
if (bind_dev) {
// Bind to specific device.
if (setsockopt(s, SOL_SOCKET, SO_BINDTODEVICE,
bind_dev, strlen(bind_dev) + 1)) {
perror("Error binding to device");
return -1;
}
}
return s;
}
The solution, as hinted by the Linux Advanced Routing and Traffic Control guide, is to turn off reverse path filtering. Not sure which of the three interfaces needed to have it turned off, but doing
echo 0 > /proc/sys/net/ipv4/conf/all/rp_filter
made it work.

How to get IP used by sendto function?

When the sender has multiple network cards, this function sendto chooses random ip to send the packet.
So get the ip address used by sendto?
Code:
fd = socket(AF_INET, SOCK_DGRAM, 0);
sendto(fd, buf, len, 0, (struct sockaddr*)&servaddr, sizeof(servaddr));
It doesn't choose a random IP. It uses the OS's routing table to decide which local IP has the best chance of routing the data to the destination address. However, there is no way to query which IP sendto() actually chose to use. You could access the OS's routing table directly and try to figure it out manually, but the better option is to just bind() the socket to the specific IP that you want sendto() to use as the sending IP, eg:
fd = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in localaddr;
memset(&localaddr, 0, sizeof(localaddr));
localaddr.sin_family = AF_INET;
localaddr.sin_addr.s_addr = inet_addr("192.168.0.1"); // the desired local IP
bind(fd, (struct sockaddr*)&localaddr, sizeof(localaddr));
sendto(fd, buf, len, 0, (struct sockaddr*)&servaddr, sizeof(servaddr));

Winsock2 - how to open a TCP socket that allows recv() with MSG_WAITALL?

In this code:
// error checking is omitted
// init Winsock2
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
// connect to server
struct addrinfo *res = NULL, *ptr = NULL, hints;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
getaddrinfo(server_ip, "9999", &hints, &res);
SOCKET client_socket = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
connect(client_socket, res->ai_addr, (int)res->ai_addrlen);
freeaddrinfo(res);
res = NULL;
// read the data
unsinged int size1;
if (recv(client_socket, (char*)&size1, sizeof(int), MSG_WAITALL) == SOCKET_ERROR)
{
return WSAGetLastError();
}
(note the MSG_WAITALL flag in recv()) everything works fine, expect for recv(). WSAGetLastError() returns WSAEOPNOTSUPP.
MSDN states that
Note that if the underlying transport does not support MSG_WAITALL, or if the socket is in a non-blocking mode, then this call will fail with WSAEOPNOTSUPP. Also, if MSG_WAITALL is specified along with MSG_OOB, MSG_PEEK, or MSG_PARTIAL, then this call will fail with WSAEOPNOTSUPP. This flag is not supported on datagram sockets or message-oriented sockets.
But it doesn't look like I'm doing something from this list. Why my recv() call doesn't work?
it doesn't look like I'm doing something from this list.
Yes, you are - the very first item on the list:
the underlying transport does not support MSG_WAITALL
Microsoft's default TCP transport provider does not support MSG_WAITALL. recv(), and Winsock in general, is not limited to just Microsoft's TCP provider. It supports 3rd party providers, and any transport protocols that the provider supports - TCP, UDP, IPX, ICMP, RAW, etc.
When using Microsoft's TCP, if you want recv() to wait until all of the requested TCP data has been received, you have to set the socket to blocking mode (its default mode) and then set the flags parameter of recv() to 0. But even that is not guaranteed, recv() can return with fewer bytes than requested, so you should be prepared to call recv() in a loop until all intended bytes have actually been received.