Search code examples
androidc++socketsudpsendto

android ndk sockets Network Unreachable


I don't know if this is in the way I'm handling Android, or a problem with my native code, or both.

I am setting up a udp socket in C++ (wrappers generated by swig):

udpSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
        if (udpSocket < 0)
        {
            pthread_mutex_unlock(&csOpenCloseUdp);
            throw IOException("Failed to open socket");
        }


        char bAllowMultiple = true;
        setsockopt(udpSocket, SOL_SOCKET, SO_REUSEADDR, &bAllowMultiple, sizeof(bAllowMultiple));
        setsockopt(udpSocket, IPPROTO_IP, IP_MULTICAST_TTL, (char *)&hopLimit, sizeof(hopLimit));
        setsockopt(udpSocket, IPPROTO_IP, IP_MULTICAST_IF, (char *)&localAddr, sizeof(localAddr));

        // Set to non-blocking mode
        unsigned long bMode = 1;
        ioctl( udpSocket, FIONBIO, &bMode );

        // Create the local endpoint
        sockaddr_in localEndPoint;
        localEndPoint.sin_family = AF_INET;
        localEndPoint.sin_addr.s_addr = localAddr.s_addr;
        localEndPoint.sin_port = groupEndPoint.sin_port;

        // Bind the socket to the port
        int r = bind(udpSocket, (sockaddr*)&localEndPoint, sizeof(localEndPoint));
        if (r == SOCKET_ERROR)
        {
            //LeaveCriticalSection(&csOpenCloseUdp);
            pthread_mutex_unlock(&csOpenCloseUdp);
            close();
            throw IOException("Failed to bind port");
        }


        // Join the multicast group
        struct ip_mreq imr;
        imr.imr_multiaddr = groupEndPoint.sin_addr;
        imr.imr_interface.s_addr = localAddr.s_addr;
        setsockopt(udpSocket, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*)&imr, sizeof(imr));

The socket is not throwing any exceptions, and after this it has some value not INVALID_SOCKET.

When I try to send a packet though,

int r = sendto(udpSocket, (char*)dataToSend, (size_t)length, 0, (sockaddr*)&groupEndPoint, (socklen_t)sizeof(groupEndPoint));

I get errno 101: Network is unreachable.

I'm quite new to socket programming, and I know sockets in Android is a bad way to start, but the fact is I have to get this done and have very little time. Does anyone here know of a likely reason to get Network Unreachable? Has anyone tried playing with UDP on Android and can shed some light?


Solution

  • SOLVED:

    I just had to monkey with the ethernet settings on the device to get it to talk to my laptop. for some reason it didn't like using the dedicated link, so I'm going through the local network router and it's working. now getting different issues, but this one's done